C# 通过c创建xml根节点
我想创建一个xml文档和根元素,如下所示:C# 通过c创建xml根节点,c#,xml,C#,Xml,我想创建一个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#"> 但我有一个例外:名称中不能包含“”字符(十六进制值0x20)。等等 如何制作这个元素? 谢谢。用于构建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#">
但我有一个例外:名称中不能包含“”字符(十六进制值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);
如果您可以考虑使用LINQtoXML,这里有一个替代方案。
// Your data
var users = new List<User> {
new User { Name = "John", Age = 42 },
new User { Name = "Jane", Age = 39 }
};
// Project the data into XElements
var userElements =
from u in users
select
new XElement("user", u.Name,
new XAttribute("age", u.Age));
// Build the XML document, add namespaces and add the projected elements
var doc = new XDocument(
new XElement("RDF",
new XAttribute(XNamespace.Xmlns + "cim",
XNamespace.Get("http://iec.ch/TC57/2009/CIM-schema-cim14#")),
new XAttribute(XNamespace.Xmlns + "rdf",
XNamespace.Get("http://www.w3.org/1999/02/22-rdf-syntax-ns#")),
userElements
)
);
doc.Save(@"c:\xml-test.xml");
我马上就要哭了。。。这不是创建XML的方式。哭是没有帮助的。您是特别想像那样逐个元素构建XmlDocument元素,还是可以使用它?我想从列表和it属性中逐个元素创建XML文档元素;您可能还想研究XmlSerialization,它可以获取对象列表并为它们生成XML—还值得研究xsd.exe,它可以获取适当的xsd文件,并为您生成C或VB.Net类,这些类将通过XmlSerialization进行序列化/反序列化。
// Your data
var users = new List<User> {
new User { Name = "John", Age = 42 },
new User { Name = "Jane", Age = 39 }
};
// Project the data into XElements
var userElements =
from u in users
select
new XElement("user", u.Name,
new XAttribute("age", u.Age));
// Build the XML document, add namespaces and add the projected elements
var doc = new XDocument(
new XElement("RDF",
new XAttribute(XNamespace.Xmlns + "cim",
XNamespace.Get("http://iec.ch/TC57/2009/CIM-schema-cim14#")),
new XAttribute(XNamespace.Xmlns + "rdf",
XNamespace.Get("http://www.w3.org/1999/02/22-rdf-syntax-ns#")),
userElements
)
);
doc.Save(@"c:\xml-test.xml");