2014-04-09 47 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" /> 
相关问题