2012-04-05 8 views
0

I XML in das folgende Formular generieren müssen:Make XML in C# mit Namespaces

<ns1:root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2"> 
    <ns2:item ns2:param="value" /> 
</ns1:root> 

Ich benutze diesen Code:

XmlDocument xDoc = new XmlDocument(); 
XmlElement xRootElement = (XmlElement)xDoc.AppendChild(xDoc.CreateElement("ns1:root")); 
xRootElement.SetAttribute("xmlns:ns1", "http://example.com/xmlns1"); 
xRootElement.SetAttribute("xmlns:ns2", "http://example.com/xmlns2"); 
XmlElement xElement = (XmlElement)xRootElement.AppendChild(xDoc.CreateElement("ns2:item")); 
xElement.SetAttribute("ns2:param", "value"); 

Aber das Ergebnis ist folgendes:

<root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2"> 
    <item param="value" /> 
</root> 

Danke für den Rat.

+0

[hier] (http://msdn.microsoft.com/en-us/library/bb387075.aspx) Beispiele sind wie xmls mit Namespace erstellen – Reniuz

Antwort

0

XmlElement xElement = (XmlElement) xRootElement.AppendChild (xDoc.CreateElement ("ns2: item" , "http://example.com/xmlns2"));

Gab mir:

<root xmlns:ns1="http://example.com/xmlns1" xmlns:ns2="http://example.com/xmlns2"> 
    <ns2:item param="value" /> 
</root> 

By the way, "ns2:param" nicht notwendig ist. XML-Attribute gehören zu demselben Namespace wie das Element.

0

Try this:

XmlDocument xDoc = new XmlDocument(); 
XmlElement xRootElement = (XmlElement)xDoc.AppendChild(xDoc.CreateElement("ns1:root")); 
xRootElement.SetAttribute("xmlns:ns1", "http://example.com/xmlns1"); 
xRootElement.SetAttribute("xmlns:ns2", "http://example.com/xmlns2"); 
XmlElement xElement =  (XmlElement)xRootElement.AppendChild(xDoc.CreateElement("item", "http://example.com/xmlns1")); 
xElement.SetAttribute("param", "http://example.com/xmlns1", "value");