This may be a beginner xml question, but how can I generate an xml document that looks like the following?
<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com"> <ci:field1>test</ci:field1> <ca:field2>another test</ca:field2> </root>
If I can get this to be written, I can get the rest of my problem to work.
Ideally, I'd like to use LINQ to XML (XElement, XNamespace, etc.) with c#, but if this can be accomplished easier/better with XmlDocuments and XmlElements, I'd go with that.
Thanks!!!
When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".
The namespace prefix is used as an alias for the complete namespace identifier. The parser sets XML-NAMESPACE-PREFIX before transferring control to the processing procedure when the operand of the XML PARSE statement is an alphanumeric data item and the RETURNING NATIONAL phrase is not specified.
The XElement class is one of the fundamental classes in LINQ to XML. It represents an XML element. The following list shows what you can use this class for: Create elements. Change the content of the element.
Here is a small example that creates the output you want:
using System; using System.Xml.Linq; class Program { static void Main() { XNamespace ci = "http://somewhere.com"; XNamespace ca = "http://somewhereelse.com"; XElement element = new XElement("root", new XAttribute(XNamespace.Xmlns + "ci", ci), new XAttribute(XNamespace.Xmlns + "ca", ca), new XElement(ci + "field1", "test"), new XElement(ca + "field2", "another test")); } }
Try this code:
string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName); string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`
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