繁体   English   中英

如何摆脱子元素中的空名称空间“ xmlns =”“”?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM