I'm building some xml using XmlWriter using a valid xml file as my template. In the file, I have this line: <ds:Signature>
So, I did this in C#:
writer.WriteStartElement("ds:Signature");
But it gives me an error of invalid character 0x3A, which is a colon. Is there a way for me to build that line of xml using XmlWriter?
In your example, "ds" refers to an xml namespace, and in correct XML you can't use it without declaring it, either in a node or one of its ancestors, earlier in the file.
XmlWriter
is aware of namespaces, forces you to create correct XML. It remembers namespaces when you use them.
This means that you can do the following:
using (var x = XmlWriter.Create("test.xml"))
{
x.WriteStartElement("ds", "ParentNode", "namespace");
x.WriteStartElement("ds", "Signature", "namespace");
x.WriteEndElement();
x.WriteEndElement();
x.Flush();
x.Close();
}
which will produce the following:
<?xml version="1.0" encoding="utf-8"?>
<ds:ParentNode xmlns:ds="namespace">
<ds:Signature />
</ds:ParentNode>
This tells somebody reading the xml that "ParentNode" and "Signature" are defined in the namespace "namespace", which is assigned the prefix "ds" by the xmlns:ds="namespace"
attribute.
This is pretty useful, but if you want something simpler, and you just want to spit out text, I'd say just use a StreamWriter
:
using (var s = new StreamWriter("test.xml"))
{
s.WriteLine("<ds:Signature>");
s.Flush();
s.Close();
}