通过c#创建xml rootNode [英] Create xml rootNode via c#

查看:40
本文介绍了通过c#创建xml rootNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create a xml document and root element like this:

<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");

但我有例外:' ' 字符,十六进制值 0x20,不能包含在名称中. 等等.

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

How to make this element? Thanks.

推荐答案

您用于构建 XML 的方法实际上是构建对象树(而不是作为它们的文本表示),因为对于 Schemas,您有告诉文档有关它们的信息:

The method you're using for building XML is actually building a tree of objects (rather than as the textual representation of them), for for Schemas, you have to tell the document about them:

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#创建xml rootNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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