2010-02-19 92 views
8

我有一個列表對象生成XML的函數:的XElement添加函數添加的xmlns = 「」 到的XElement

public XDocument ToXML() 
{ 
    foreach (var row in this) 
    { 
     var xml = row.ToXml(); 
     template.Root.Add(xml); 
    } 
    return template; 
} 

template.ToString()讀取:<RootElement xmlns="urn:testTools">

xml reads:<Example><SubElement>testData</SubElement></Example>

添加函數執行了模板後.ToString() reads: <RootElement xmlns="urn:testTools"><Example xmlns=""><SubElement>testData</SubElement></Example>

所以出於某種原因,有一個空的名稱空間添加,我怎麼能阻止它這樣做?

回答

7

將Example和SubElement元素的名稱空間設置爲與RootElement相同。它添加了xmlns =「」來清除這些元素的名稱空間。

+0

好吧我現在明白了爲什麼它那樣做,謝謝! 但它是唯一有用的,如果你合併不同的XML,不同的命名空間,而不是創建一個單一的XML文檔。此外,一個空的名稱空間標記是無效的XML。 – JJoos 2010-02-19 15:57:12

+1

@JJoos:一個空的命名空間肯定是有效的XML。是什麼讓你覺得它不是?另外,請記住單個XML文檔可能具有來自許多命名空間的元素和屬性。 – 2010-03-16 19:36:12

+0

@約翰桑德斯 你是對的,認爲這是非法的,因爲: http://www.w3.org/TR/REC-xml-names/第2.2節的第一行。 有點混淆。謝謝。 – JJoos 2010-03-19 09:07:15

0

這可能是你的根必須正確關閉:

<RootElement xmlns="urn:testTools"> to <RootElement xmlns="urn:testTools"/> 
0

我用正則表達式的替換元素解決它。 Foole的解決方案不起作用,因爲我現在並不總是那個代碼中的確切名稱空間。

因此,這裏是我的骯髒的黑客的作品:

template = XDocument.Parse(new Regex("<ElementName.*>") 
    .Replace(template.ToString(SaveOptions.DisableFormatting), "<ElementName>")); 
+4

小心你的正則表達式。 XML不是一種常規語言,所以一般來說,正則表達式不應用於XML。 – 2010-03-16 19:38:07

9

這裏是沒有空的命名空間的XML輸出的例子。注意奇怪的以Linq爲中心的語法rootNamespace +「MyElementName」,這是祕密。這是與整個文檔相同的命名空間,因此不需要添加xmlns。這是連接一個XNamespace +一個字符串,這是一個適用於Linq的「+」重載,並且Linq知道如何處理。 (如果沒有Linq,可能會出現連接字符串和非字符串類型的編譯錯誤)。注意這是針對C#項目文件執行的,該文件是一個方便的Xml文件。將其輸出到控制檯或richtextbox控件。然後取出「rootNamespace +」並注意區別。

 XDocument doc = null; 

     using (StreamReader streamReader = 
      new StreamReader(@"myXml.csproj")) 
     { 
      doc = XDocument.Load(streamReader, LoadOptions.None); 
     } 
     XNamespace rootNamespace = doc.Root.Name.NamespaceName; 

     // A search which finds the ItemGroup which has Reference 
     // elements and returns the ItemGroup XElement. 
     XElement element = doc.Descendants().Where(p => p.Name.LocalName == "ItemGroup" 
      && p.Descendants().First<XElement>().Name.LocalName == "Reference").First<XElement>(); 

     // Create a completly new element with sub elements. 
     XElement referenceElement = new XElement(rootNamespace + "Reference", 
      new XElement(rootNamespace + "SpecificVersion", bool.FalseString), 
      new XElement(rootNamespace + "HintPath", "THIS IS A HINT PATH")); 

     // Add the new element to the main doc, to the end of the Reference elements. 
     element.Add(referenceElement); 

     // Add an attribute after the fact for effect. 
     referenceElement.SetAttributeValue("Include", "THIS IS AN INCLUDE"); 

     rtb.Text = doc.ToString(SaveOptions.None); 
+0

謝謝你看起來像一個非常好的解決方案!我會在下次遇到這個問題時嘗試一下。 – JJoos 2010-04-28 08:32:09

+1

謝謝!這非常有幫助! – 2013-07-21 23:36:18

+1

謝謝。這太棒了! +1 – 2015-09-22 12:03:13

相關問題