创建无命名空间声明XML元素 [英] Creating XML Elements without namespace declarations

查看:125
本文介绍了创建无命名空间声明XML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试一个新的的PropertyGroup元素添加到下面的XML文件

I attempting to add a new "PropertyGroup" element to the following XML file

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



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

The code I am using is as follows (note there is other logic that has been removed) :

        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文档中的下列新元素:

This yields the following new element in the XML document :

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



我要如何在元素上摆脱空间声明中?

How do I get rid of the namespace declaration on the element?

推荐答案

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

You need to specify the XML namespace for all elements you add to the 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 这样的),该元素将得到可怕的空命名空间。

If you don't do so for any element (or if you use InnerXml like that), that element will get the dreaded empty namespace.

这篇关于创建无命名空间声明XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆