![](/img/trans.png)
[英]How do I get rid of the xmlns declarations inserted by the XmlSerializer?
[英]How do I get rid of empty namespaces “xmlns=”“” in subelements?
我有這個
XNamespace ns = "http://something0.com";
XNamespace xsi = "http://something1.com";
XNamespace schemaLocation = "http://something3.com";
XDocument doc2 = new XDocument(
new XElement(ns.GetName("Foo"),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi.GetName("schemaLocation"), schemaLocation),
new XElement("ReportHeader", GetSection()),
GetGroup()
)
);
它給
<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://something1.com"
xsi:schemaLocation="http://something3.com"
xmlns="http://something0.com">
<ReportHeader xmlns="">
...
</ReportHeader>
<Group xmlns="">
...
</Group>
</Foo>
但是我不想要這個結果,怎么辦呢? (注意缺少xmlns=""
。)
<?xml version="1.0" encoding="utf-8"?>
<Foo xmlns:xsi="http://something1.com"
xsi:schemaLocation="http://something3.com"
xmlns="http://something0.com">
<ReportHeader>
...
</ReportHeader>
<Group>
...
</Group>
</Foo>
這里的問題是您將文檔的默認名稱空間設置為“ http://something0.com”,但是隨后追加了不在該名稱空間中的元素-它們位於空名稱空間中。
您的文檔指出其默認名稱空間為xmlns =“ http://something0.com”,但隨后您會添加空名稱空間中的元素(因為添加元素時未提供其名稱空間),因此它們是所有文件都顯式標記為xmlns =''以表明它們不在文檔的默認名稱空間中。
這意味着有兩種解決方案來擺脫xmlns =“”,但是它們具有不同的含義:
1)如果您是絕對要在根元素(指定文檔的默認名稱空間)中使用xmlns="http://something0.com"
-那么要“消失” xmlns =“”,您需要在創建元素時提供以下名稱空間:
// create a ReportHeader element in the namespace http://something0.com
new XElement(ns + "ReportHeader", GetSection())
2)如果這些元素不是要放在“ http://something0.com”命名空間中,則您不必將其作為默認值添加到文檔頂部(xmlns =“ http:// something0。 com”在根元素上)。
XDocument doc2 = new XDocument(
new XElement("foo", // note - just the element name, rather s.GetName("Foo")
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
您期望的樣本輸出建議這兩個選擇中的前一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.