简体   繁体   English

为XML元素创建名称空间

[英]Creating namespace for XML element

I have problem with adding new node (with namespace) to my xml document which is used to generating xaml. 我在将新节点(带有名称空间)添加到用于生成xaml的xml文档中时遇到问题。 I'm doing it like this: 我正在这样做:

XmlElement richTextColumns = xmlDoc.CreateElement("local2:RichTextColumns");

but i receive error 0xC00CE01D (while calling xmlDoc.getxml). 但我收到错误0xC00CE01D(在调用xmlDoc.getxml时)。 I have tried adding attribute xmlns:local2="using:App2.Common" to xmlDoc: 我尝试将属性xmlns:local2 =“ using:App2.Common”添加到xmlDoc中:

var att = xmlDoc.CreateAttribute("xmlns:local2");
att.InnerText = "using:Dictionary.Common";
xmlDoc.Attributes.SetNamedItem(att);

it results in this error 导致这个错误

Object reference not set to an instance of an object. 你调用的对象是空的。

Thank you in advance :) 先感谢您 :)

According to http://msdn.microsoft.com/en-us/library/aa335908(v=vs.71) , the CreateAttribute method with a single parameter does not set the namespace, but the name of the element. 根据http://msdn.microsoft.com/zh-cn/library/aa335908(v=vs.71) ,带有单个参数的CreateAttribute方法不会设置名称空间,而是设置元素的名称。 Try to use one of the other permutations of this method. 尝试使用此方法的其他排列之一。

You can create an element as you would typically do and then load the document back and add the namespace atribute you are looking to add. 您可以像通常那样创建一个元素,然后将文档加载回去,并添加要添加的名称空间属性。

  XmlDocument doc = new XmlDocument();
    doc.LoadXml("link to yuor xml");
    XNamespace xmlns = "local2";
    public static void SetDefaultXmlNamespace(XElement xelem, XNamespace xmlns)
    {

        foreach(var e in xelem.Elements())
            e.SetDefaultXmlNamespace(xmlns);
    }

    doc.Root.SetDefaultXmlNamespace("local2")

如果要创建具有特定名称空间的元素,请使用以下调用

xmlDoc.CreateElementNS("using:Dictionary.Common", "local2:elementName")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM