Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create xml rootNode via c#

Tags:

c#

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#">

I try create this like that:

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

But i have exeption :The ' ' character, hexadecimal value 0x20, cannot be included in a name. Or so on.

How to make this element? Thanks.

like image 380
user2545071 Avatar asked Oct 04 '22 07:10

user2545071


2 Answers

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);
like image 81
Rowland Shaw Avatar answered Oct 12 '22 07:10

Rowland Shaw


If you can consider using Linq to XML, here's an alternative.

// 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");
like image 42
Mikael Östberg Avatar answered Oct 12 '22 07:10

Mikael Östberg