2012-04-05 5 views
0

мне нужно сгенерировать XML в следующем виде:Сделать XML в C# с пространствами имен

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

Я использую этот код:

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"); 

Но результат состоит в следующем:

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

Спасибо за совет.

+0

[Здесь] (http://msdn.microsoft.com/en-us/library/bb387075.aspx) является примерами, как создать XMLs с пространством имен – Reniuz

ответ

0

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

Дал мне:

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

Кстати, "ns2:param" не является необходимым. Атрибуты XML принадлежат к тому же пространству имен, что и элемент.

0

Попробуйте это:

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"); 
Смежные вопросы