【问题标题】:Create xml rootNode via c#通过c#创建xml rootNode
【发布时间】:2013-08-09 07:24:59
【问题描述】:

我想像这样创建一个 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");

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

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

【问题讨论】:

  • 我快要哭了...这不是您创建 XML 的方式。
  • 哭也没有用。
  • 你是特别想像这样逐个元素地构建XmlDocument,还是只使用XmlDocument.LoadXml()
  • 我想从我的 List 和它的属性中逐个元素地创建 XML 文档;
  • 您可能还想查看 XmlSerialization,它可以获取对象列表并为它们生成 XML - 还值得查看可以获取适当 XSD 文件并生成 C#(或 VB)的 xsd.exe .Net) 类将通过 XmlSerialisation 进行序列化/反序列化。

标签: c# xml


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您可以考虑使用 Linq to XML,这里有一个替代方案。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2012-02-05
      • 2022-12-07
      • 2010-10-25
      相关资源
      最近更新 更多