When generating XML in C#, Is there a problem with generating it as a string? In the past I've found generating XML programatically very verbose and convoluted. Creating the xml through string concatenation/a string builder seems much easier but, it feels like bad practice.
Should I generate XML as a string?
XML Schema defines in a way what an XML document contains, therefore, XSD defines the string so, it can be defined as a value that contains character strings also has Unicode character given by XML and represented using the type xs: string, while this type has a white space character and maintained by the processor as ...
In this article, you will learn three ways to read XML files as String in Java, first by using FileReader and BufferedReader, second by using DOM parser, and third by using open-source XML library jcabi-xml.
This example writes the object from a class to an XML file using the XmlSerializer class.
Efficient XML performs well within the W3C required thresholds for compactness. When schema optimizations are used, Efficient XML is competitive with hand-optimized binary formats and is generally smaller than ASN. 1 PER. When compression is used, Efficient XML is consistently smaller than gzip.
The XDocument, XElement and XAttribute classes make xml generation in C# much easier to do. Than using the XmlDocument or XmlWriter.
As an example, to produce this:
<RootElement>
<ChildElement Attribute1="Hello" Attribute2="World" />
<ChildElement Attribute1="Foo" Attribute2="Bar" />
</RootElement>
You can do this:
XDocument xDocument = new XDocument(
new XElement("RootElement",
new XElement("ChildElement",
new XAttribute("Attribute1", "Hello"),
new XAttribute("Attribute2", "World")
),
new XElement("ChildElement",
new XAttribute("Attribute1", "Foo"),
new XAttribute("Attribute2", "Bar")
)
)
);
Have you tryed Linq to Xml? it is not very verbose:
XElement xml = new XElement("contacts",
new XElement("contact",
new XAttribute("id", "1"),
new XElement("firstName", "first"),
new XElement("lastName", "last")
),
new XElement("contact",
new XAttribute("id", "2"),
new XElement("firstName", "first2"),
new XElement("lastName", "last2")
)
);
Console.Write(xml);
Before you think about generating XML using string concatenation instead of a proper library, please go and read the XML specification. Pay particular attention to niceties such as charsets and character references.
You can do it now. I'll wait.
Now ask yourself - do you really want to have to ensure that your concatenated string is valid according to all those rules and write all the helper functions yourself, or do you want to use a well tested library where all that logic has been encapsulated for you?
Good.
Glad that's sorted.
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