[英]Namespace with colon as attribute of xml file in C#
我想生成一個XML代碼,例如以下示例:-
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns ="abc.xyz.xsd" xmlns:xsi="http://namespace">
</Root>
我的C#代碼如下所示:
XNamespace xsi = "http://namespace";
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("Root",
new XAttribute("xmlns", "abc.xyz.xsd"),
new XAttribute(XNamespace.Xmlns + "xsi", xsi)
);
此代碼在保存時會出錯。 我究竟做錯了什么?
由於您正在使用名稱空間,因此應為您的Root
元素添加名稱空間(名稱空間+“ Root”)。
像這樣:
XNamespace xsi = "http://namespace";
XNamespace ns = "abc.xyz.xsd";
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(ns + "Root",
new XAttribute("xmlns", ns),
new XAttribute(XNamespace.Xmlns + "xsi", xsi)));
請參閱有關創建具有名稱空間的文檔的MSDN文章 。
您可以使用單個名稱空間
XNamespace xsi = "http://namespace";
XDocument doc1 = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(xsi + "Root",
new XAttribute("xmlns", "abc.xyz.xsd"),
new XAttribute(XNamespace.Xmlns + "xsi", "http://namespace"),
new XElement(xsi + "Child",
new XElement(xsi + "DifferentChild", "other content")
)
));
請參閱此作為參考https://msdn.microsoft.com/en-us/library/bb387075.aspx
輸出將如下所示
<?xml version="1.0" encoding="utf-8"?>
<xsi:Root xmlns="abc.xyz.xsd" xmlns:xsi="http://namespace">
<xsi:Child>
<xsi:DifferentChild>other content</xsi:DifferentChild>
</xsi:Child>
</xsi:Root>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.