0

我有这个

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>
4

1 回答 1

3

您的问题是您将文档的默认命名空间设置为“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),

您期望的示例输出表明这两种选择中的前者。

于 2012-04-18T08:26:05.950 回答