【问题标题】:How do I get rid of empty namespaces "xmlns=""" in subelements?如何摆脱子元素中的空命名空间“xmlns="""?
【发布时间】:2012-04-29 15:10:49
【问题描述】:

我有这个

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>

【问题讨论】:

    标签: c# xml namespaces xml-namespaces


    【解决方案1】:

    您的问题是您将文档的默认命名空间设置为“http://something0.com”,但随后附加了不在此命名空间中的元素 - 它们在 empty 命名空间。

    您的文档声明它具有 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),
    

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

    【讨论】:

    • 感谢这对我来说有点道理,但我仍然不知道该怎么做。
    • 我只想像往常一样在Foo 之后做同样的事情,但在ReportHeaderGroup 之后什么都没有:)
    • 如果我用Foo 替换ns.GetName("Foo"),我不会在Foo 之后得到xmlns="http://something0.com",如果这有意义的话。 (它消除了很多)
    • 我看到您为答案和大量编辑付出了很多努力。我试图跟上。我需要读几遍才能理解它,然后进行测试。 :)
    • 酷 - 这是否意味着您的问题现在解决了?这里要理解的是 什么 命名空间实际上是关于文档及其元素的;单击此按钮后,您看到的行为将变得有意义(以及如何解决它们)。看看这个先前的答案 - 如果还没有的话,它应该很清楚:stackoverflow.com/questions/1181888/what-does-xmlns-in-xml-mean/…
    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多