gpt4 book ai didi

c# - 通过c#创建xml rootNode

转载 作者:数据小太阳 更新时间:2023-10-29 02:30:49 24 4
gpt4 key购买 nike

我想像这样创建一个 xml 文档和根元素:

<rdf:RDF xmlns:cim="http://iec.ch/TC57/2009/CIM-schema-cim14#"

xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">

我尝试这样创建:

 XmlDocument doc = new XmlDocument();
XmlNode rootNode = doc.CreateElement("rdf:RDF xmlns:cim="http://iec.ch/TC57/2009/CIM-schema-cim14#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">");
doc.AppendChild(rootNode);

XmlNode userNode = doc.CreateElement("user");
XmlAttribute attribute = doc.CreateAttribute("age");
attribute.Value = "42";
userNode.Attributes.Append(attribute);
userNode.InnerText = "John Doe";
rootNode.AppendChild(userNode);

userNode = doc.CreateElement("user");
attribute = doc.CreateAttribute("age");
attribute.Value = "39";
userNode.Attributes.Append(attribute);
userNode.InnerText = "Jane Doe";
rootNode.AppendChild(userNode);

doc.Save("C:/xml-test.xml");

但我有异常(exception):' ' 字符,十六进制值 0x20,不能包含在名称中。 等等。

如何制作这个元素?谢谢。

最佳答案

您用于构建 XML 的方法实际上是构建一个对象树(而不是作为它们的文本表示),因为对于模式,您必须将它们告诉文档:

XmlDocument doc = new XmlDocument();
XmlSchemaSet xss = new XmlSchemaSet();
xss.Add("cim", "http://iec.ch/TC57/2009/CIM-schema-cim14#");
xss.Add("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
doc.Schemas = xss;
XmlNode rootNode = doc.CreateElement("rdf:RDF"); // This overload assumes the document already knows about the rdf schema as it is in the Schemas set
doc.AppendChild(rootNode);

关于c# - 通过c#创建xml rootNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18141928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com