2011-03-30 87 views
8

我尝试了新的“的PropertyGroup”元素添加到下面的XML文件没有命名空间声明创建XML元素

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0"> 
    <PropertyGroup> 
    <ProjectGuid>{00AA7ECA-95A0-0000-0000-AD4D2E056BFE}</ProjectGuid> 
    <OutputType>Library</OutputType> 
    <AppDesignerFolder>Properties</AppDesignerFolder> 
    <RootNamespace>testnS</RootNamespace> 
    <AssemblyName>testname</AssemblyName> 
    <PluginId>4B84E5C0-EC2B-4C0C-8B8E-3FAEB09F74C6</PluginId> 
    </PropertyGroup> 
</Project> 

我使用的代码如下(注意,已删除其他逻辑) :

 XmlTextReader reader = new XmlTextReader(filename); 
     XmlDocument doc = new XmlDocument(); 

     doc.Load(reader); 
     reader.Close(); 

     XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); 
     ns.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003"); 

     XmlElement root = doc.DocumentElement; 
     XmlNode refNode = root.SelectSingleNode("x:Project", ns); 

     root.SelectSingleNode("Project", ns); 

     XmlElement newElement = doc.CreateElement("PropertyGroup", "http://schemas.microsoft.com/developer/msbuild/2003"); 
     newElement.InnerXml = "<value>test</value>"; 
     root.InsertAfter(newElement, refNode); 
     doc.Save(filename); 

这产生XML文档中的下列新元素:

<PropertyGroup> 
    <value xmlns="">test</value> 
</PropertyGroup> 

如何摆脱元素上的名称空间声明?

+0

你必须在这里使用InnerXml属性吗?明确地做它会更容易。 (如果这是一个选项,使用LINQ to XML会更容易。) – 2011-03-30 07:43:08

+0

不确定LINQ to XML - LINQ对我来说是一个未知数...:-) – 2011-03-30 07:56:29

+0

但我刚刚发现这个:http://stackoverflow.com/questions/2013165/linq-to-xml-adding-an-element – 2011-03-30 07:59:10

回答

10

您需要指定XML命名空间所有元素添加到DOM:

XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); 
ns.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003"); 

XmlElement root = doc.DocumentElement; 
XmlNode refNode = root.SelectSingleNode("x:Project", ns); 

XmlElement newElement = doc.CreateElement(
    "PropertyGroup", 
    "http://schemas.microsoft.com/developer/msbuild/2003"); 
var value = newElement.AppendChild(doc.CreateElement(
    "value", 
    "http://schemas.microsoft.com/developer/msbuild/2003")); 
value.AppendChild(doc.CreateTextNode("test")); 

root.InsertAfter(newElement, refNode); 

如果你没有任何元素这样做(或者,如果您使用InnerXml那样),那元素将得到可怕的空名称空间。

3

出现这种情况的原因是,你已经通过具有根节点的命名空间定义中定义的默认命名空间的文件成为“http://schemas.microsoft.com/developer/msbuild/2003”:

xmlns="http://schemas.microsoft.com/developer/msbuild/2003" 

你然后进行添加元素它不在文档的命名空间('空'命名空间)中。这已经

xmlns="" 

合格,因为如果不是那就意味着新的元素是在前面提到的微软命名空间 - 它不是(或者说 - 你没有问它是)。

因此,要么:

  • 你真的想 新元素是在微软的命名空间 - 在 你需要这么说这种情况。该 最简单的方法是使用的createElement 和供应的命名空间,虽然 你可能它明确 与xmlns属性您 InnerXml(这是不添加节点的一个特别 很好的方式)的状态。

  • 你真的想要这个元素 空命名空间,你 在这种情况下,可能是更好的排位赛都 不在同一个命名空间 前缀 空命名空间中的其他节点。

我怀疑你想要前者。

有关命名空间的快速概述可参见here