每当我在我的 xml 文档中插入一个元素时,系统都会向它添加一个 xmlns="" 属性。我该如何摆脱它?为什么会在那里?我使用非常简单的 linqtoxml。
我有一个简单的 XML 文件(注意没有 Xml 声明行,它包含一个命名空间):
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup>
</PropertyGroup>
</Project>
我执行以下操作:
// 1. Read in the Xml file
XDocument testXml = XDocument.Load(@"C:\test.xml");
// 2. Add in the extra node
XNamespace ns = testXml.Root.Attribute("xmlns").Value; // Get the existing namespace
XElement newElement = new XElement("MyNewElement", "12345"); // Create the new element
testXml.Element( ns + "Project").Add( newElement ); // Insert the new element into the document
// 3. Write To Disk (without the xml header line)
TextWriter tw = File.CreateText(@"C:\test2.xml");
tw.Write(testXml.ToString());
tw.Close();
查看文件时,我得到:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
<PropertyGroup></PropertyGroup>
<MyNewElement xmlns="">12345</MyNewElement>
</Project>
我需要摆脱 xmlns="" 位。我相信在添加新元素时需要包含命名空间,因为原始文档有一个命名空间。我试图插入元素:
testXml.Element( "Project").Add( newElement );
但它一直给我一个空引用异常,我假设这是因为元素需要命名空间名称。
我想再次解析它并删除所有 xmlns="" 属性,但它似乎不起作用;我不断收到空引用异常。我可能在这里缺乏对命名空间的一些基本理解,但我环顾四周,似乎找不到任何提示。
谁能指出我正确的方向?
干杯杰克。