2017-06-01 60 views
0
<ftc:XX version="1.1" 
    xmlns:ftc="urn:v1" 
    xmlns="urn:v1">  
    <ftc:YY>  
    <SIN>000000</SIN>  
    <Country>CA</Country>  
    </ftc:YY> 
</ftc:XX> 

這是我需要創建的。但是當我創建它時,它顯示SIN和國家/地區標籤中的空名稱空間。我需要刪除它。任何人都可以引導我?linq to xml重複名稱空間給出空屬性

這就是我使用的代碼,

XNamespace ftc = "urn:v1"; 
XElement XX = new XElement(ftc + "XX", 
    new XAttribute(XNamespace.Xmlns + "ftc", ftc.NamespaceName), 
    new XAttribute("xmlns", ftc.NamespaceName), 
    new XAttribute("version","1.1"), 

    new XElement(ftc + "YY",      
    XElement("SIN", "000000"), 
    new XElement("Country", "CA") 
) 
) 

這個問題,我所得到的是這樣的。

<ftc:XX version="1.1" 
    xmlns:ftc="urn:v1" 
    xmlns="urn:v1">  
    <ftc:YY>  
    <SIN xmlns="">000000</SIN>  
    <Country xmlns="">CA</Country>  
    </ftc:YY> 
</ftc:XX> 

但我需要沒有這部分。

的xmlns = 「」

回答

0

SINCountry屬於urn:v1命名空間。您的文檔的默認名稱空間爲urn:v1,因此所有沒有明確名稱空間前綴的元素都將屬於該名稱空間。

當您創建這些元素時,它們位於空的名稱空間中,因此需要生成額外的名稱空間聲明。

XNamespace ftc = "urn:v1"; 
var doc = new XDocument(
    new XElement(ftc + "XX", 
     new XAttribute("version", "1.1"), 
     new XAttribute(XNamespace.Xmlns + "ftc", ftc), 
     new XAttribute("xmlns", ftc), 
     new XElement(ftc + "YY", 
      new XElement(ftc + "SIN", "000000"), 
      new XElement(ftc + "Country", "CA") 
     ) 
    ) 
); 
<XX version="1.1" xmlns:ftc="urn:v1" xmlns="urn:v1"> 
    <YY> 
    <SIN>000000</SIN> 
    <Country>CA</Country> 
    </YY> 
</XX> 

注意,因爲你明確的命名空間ftc和默認的命名空間是相等的,將像您期望的產生沒有任何前綴。就我所知,這在每個元素級別上都是不可配置的。

+0

謝謝@Jeff,是的,我同意你的意見。但在一些情況下,我必須像這樣創建。 –