2014-09-30 105 views
0
Dim soapEnvelope As XElement = New XElement(soap + "Envelope", 
             New XAttribute(XNamespace.Xmlns + "soap", soap.NamespaceName), 
             New XAttribute(soap + "encodingStyle", "http://www.w3.org/2001/12/soap-encoding"), 
             New XElement(soap + "Body", 
             New XAttribute("xmlns", "http://www.test.com"), 
             New XElement("Open", 
             New XElement("Data", 
             New XElement("Desc", _dData.Desc), 
             New XElement("Num", _dData.Num), 
             New XElement("Ref", _dData.Ref), 
             New XElement("Mnn", _dData.Mnn), 
             New XElement("Ftp", _dData.Ftp)) 
           ))) 

下面是给这个输出:的XElement自动拥有xmlns属性

<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> 
    <soap:Body xmlns="http://www.test.com"> 
    <Open xmlns=""> 
     <Data> 
     <Desc>testApp</Desc> 
     <Num>1</Num> 
     <Ref></Ref> 
     <Mnn>116</Mnn> 
     <Ftp></Ftp> 
     </Data> 
    </Open> 
    </soap:Body> 
</soap:Envelope> 

问题是为何<Open>的XElement自动获得一个xmlns="“属性

我希望同样的输出,但没有任何属性的XElement <Open>

任何帮助,将不胜感激

回答

1

这就是因为XML具有默认命名空间(xmlns="...")宣布在<Open>元素。在XML中,所有后代元素都自动从祖先继承默认名称空间,除非另有明确设置(f.e通过使用指向不同名称空间的前缀,或者通过在后代级别声明不同的默认名称空间)。

使用您尝试的代码,<Body>的后代在没有命名空间中设置。您需要使用XNamespace<Open>元素的后代设置为处于相同的默认名称空间中,例如:

XNamespace ns = "http://www.test.com" 
Dim soapEnvelope As XElement = New XElement(soap + "Envelope", 
             New XAttribute(XNamespace.Xmlns + "soap", soap.NamespaceName), 
             New XAttribute(soap + "encodingStyle", "http://www.w3.org/2001/12/soap-encoding"), 
             New XElement(soap + "Body", 
             New XAttribute("xmlns", "http://www.test.com"), 
             New XElement(ns+"Open", 
             New XElement(ns+"Data", 
             New XElement(ns+"Desc", _dData.Desc), 
             New XElement(ns+"Num", _dData.Num), 
             New XElement(ns+"Ref", _dData.Ref), 
             New XElement(ns+"Mnn", _dData.Mnn), 
             New XElement(ns+"Ftp", _dData.Ftp)) 
           ))) 
1

你需要在它的命名空间中创建的每个元素:

XNamespace t = "http://www.test.com"; 
             New XElement(t + "Open", 
             New XElement(t + "Data", 
             New XElement(t + "Desc", _dData.Desc), 
             New XElement(t + "Num", _dData.Num), 
             New XElement(t + "Ref", _dData.Ref), 
             New XElement(t + "Mnn", _dData.Mnn), 
             New XElement(t + "Ftp", _dData.Ftp))