2012-04-18 98 views
0

我有这个如何去除子元素中的空名称空间“xmlns =”“”?

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> 

但我wan't这个结果,怎么能做到呢? (注意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> 

回答

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), 

您期望的样本输出表明这两个选择的前者。

+0

感谢这对我有意义,但我仍然不知道该怎么做。 – radbyx 2012-04-18 08:31:21

+0

我只是想在'Foo'之后像'Always'一样,但在'ReportHeader'和'Group'之后没有任何东西:) – radbyx 2012-04-18 08:37:06

+0

如果我用'Foo'替换'ns.GetName(“Foo”)'',我没有得到'Foo'后的'xmlns =“http://something0.com”',如果这是有道理的话。 (它消除了很多) – radbyx 2012-04-18 08:40:55

相关问题