問題描述
我需要為元素aaa"創建一個帶有前綴xx"的屬性abc".以下代碼添加了前綴,但它也將 namespaceUri 添加到元素.
I need to create an attribute "abc" with the prefix "xx" for an element "aaa". The following code adds the prefix but it also adds the namespaceUri to the element.
所需輸出:
<mybody>
<aaa xx:abc="ddd"/>
<mybody/>
我的代碼:
XmlNode node = doc.SelectSingleNode("http://mybody");
XmlElement ele = doc.CreateElement("aaa");
XmlAttribute newAttribute = doc.CreateAttribute("xx","abc",namespace);
newAttribute.Value = "ddd";
ele.Attributes.Append(newAttribute);
node.InsertBefore(ele, node.LastChild);
以上代碼生成:
<mybody>
<aaa xx:abc="ddd" xmlns:xx="http://www.w3.org/1999/XSL/Transform"/>
<mybody/>
想要的輸出是
<mybody>
<aaa xx:abc="ddd"/>
<mybody/>
并且xx"屬性的聲明應該在根節點中完成,如:
And the declaration of the "xx" attribute should be done in the root node like :
<ns:somexml xx:xsi="http://www.w3.org/1999/XSL/Transform" xmlns:ns="http://x.y.z.com/Protocol/v1.0">
如果以 deisred 格式獲得輸出,如何獲得?如果 xml 不是這種所需的格式,則無法再對其進行處理..
How can if get the output in the deisred format? If the xml is not in this desired format then it cannot be processed anymore..
誰能幫忙?
謝謝,維姬
推薦答案
相信直接在根節點上設置相關屬性就可以了.這是一個示例程序:
I believe it's just a matter of setting the relevant attribute directly on the root node. Here's a sample program:
using System;
using System.Globalization;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
string ns = "http://sample/namespace";
XmlAttribute nsAttribute = doc.CreateAttribute("xmlns", "xx",
"http://www.w3.org/2000/xmlns/");
nsAttribute.Value = ns;
root.Attributes.Append(nsAttribute);
doc.AppendChild(root);
XmlElement child = doc.CreateElement("child");
root.AppendChild(child);
XmlAttribute newAttribute = doc.CreateAttribute("xx","abc", ns);
newAttribute.Value = "ddd";
child.Attributes.Append(newAttribute);
doc.Save(Console.Out);
}
}
輸出:
<?xml version="1.0" encoding="ibm850"?>
<root xmlns:xx="http://sample/namespace">
<child xx:abc="ddd" />
</root>
這篇關于如何在 c# .net CF 3.5 中使用 XmlDocument 向 xml 添加屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!