2014-04-09 50 views
2

我試圖用C#和.NET(2.0版,是的,2.0版)創建一個XmlDocument。我已經設置使用命名空間屬性:用XmlDocument.CreateElement()創建一個名稱空間的XML元素

document.DocumentElement.SetAttribute(
    "xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope"); 

當我創建使用新XmlElement

document.createElement("soapenv:Header"); 

...它不包括在最後的XML命名空間soapenv。任何想法爲什麼發生這種情況

更多信息:

好吧,我會盡力澄清這個問題有點。我的代碼是:

XmlDocument document = new XmlDocument(); 
XmlElement element = document.CreateElement("foo:bar"); 
document.AppendChild(element); Console.WriteLine(document.OuterXml); 

輸出:

<bar /> 

不過,我要的是:

<foo:bar /> 

回答

-1

也許你可以分享你期待什麼作爲最終的XML文檔。

但是從我瞭解你想要做的,看起來像:

<?xml version="1.0"?> 
    <soapMessage xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope"> 
     <Header xmlns="http://schemas.xmlsoap.org/soap/envelope" /> 
    </soapMessage> 

這樣的代碼來做到這一點是:

XmlDocument document = new XmlDocument(); 
    document.LoadXml("<?xml version='1.0' ?><soapMessage></soapMessage>"); 
    string soapNamespace = "http://schemas.xmlsoap.org/soap/envelope/"; 
    XmlAttribute nsAttribute = document.CreateAttribute("xmlns","soapenv","http://www.w3.org/2000/xmlns/"); 
    nsAttribute.Value = soapNamespace; 
    document.DocumentElement.Attributes.Append(namespaceAttribute); 
    document.DocumentElement.AppendChild(document.CreateElement("Header",soapNamespace)); 
+1

-1你不必明確創建'xmlns' 「屬性」。這是一個名稱空間聲明,只是創建一個使用名稱空間的元素將導致該屬性奇蹟般地出現。 –

+0

好的,我試着澄清這個問題。 我的代碼是 XmlDocument document = new XmlDocument(); XmlElement element = document.CreateElement(「foo:bar」); document.AppendChild(element); Console.WriteLine(document.OuterXml); ...它會輸出 ......它應該輸出

1

您可以通過一個命名空間分配給您的bar元素使用XmlDocument.CreateElement Method (String, String, String)

例如:

using System; 
using System.Xml; 

XmlDocument document = new XmlDocument(); 

// "foo"     => namespace prefix 
// "bar"     => element local name 
// "http://tempuri.org/foo" => namespace URI 

XmlElement element = document.CreateElement(
    "foo", "bar", "http://tempuri.org/foo"); 

document.AppendChild(element); 
Console.WriteLine(document.OuterXml); 

預期輸出:

<foo:bar xmlns:foo="http://tempuri.org/foo" /> 
相關問題