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.
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);
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With