2

每当我在我的 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="" 属性,但它似乎不起作用;我不断收到空引用异常。我可能在这里缺乏对命名空间的一些基本理解,但我环顾四周,似乎找不到任何提示。

谁能指出我正确的方向?

干杯杰克。

4

3 回答 3

1

XmlNs is "XML NameSpace" - basically the idea is the same as C++ namespaces, Java/C# packages, etc, except it's for parsing against varying XML Schemas (eg XSD, DTD).

You are creating MyNewElement without specifying its namespace, so your DOM tree is interpreting that to be the blank namespace. Since your document root specifies a non-blank namespace, the xmlns="" declaration it is inserting is correct according to your code. You need to specify the namespace on your MyNewElement before adding it to the document somehow. I'm not familiar with the LinQ XML API, but I know that in one earlier version of the .Net XML parsers, recommended practice was to use a CreateElement() call from an XmlDocument instance to correctly hoist in those settings.

Just on a wild guess based on the lookup code for the Project element, and not knowing LinQ at all, try changing:

XElement newElement = new XElement("MyNewElement", "12345");

to:

XElement newElement = new XElement(ns + "MyNewElement", "12345");
于 2009-04-07T02:09:32.120 回答
1

这不是问题的答案,但我仍然希望它告诉你。

您可以使用 save 方法将 xdocument 保存到文件中:

XDocument testXml = XDocument.Load(@"C:\test.xml");
...
testXml.Save(@"c:\test.xml"); 

无需使用 TextWriter。

于 2009-05-14T11:53:48.280 回答
0

您必须将您的命名空间有意地放在 xml 字符串中,例如:

<serveur nom='nouveau serveur'  xmlns='urn:myLogConfig'>

然后在代码中删除它:(vb)

myXelement.SetAttributeValue("xmlns", Nothing)
于 2011-04-26T15:19:49.173 回答