簡體   English   中英

XElement Add函數將xmlns =“”添加到XElement

[英]XElement Add function adds xmlns=“” to the XElement

我有一個為列表對象生成xml的函數:

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讀取: <Example><SubElement>testData</SubElement></Example>

add函數執行完template.ToString()后讀取: <RootElement xmlns="urn:testTools"><Example xmlns=""><SubElement>testData</SubElement></Example>

因此,由於某種原因,添加了一個空名稱空間,我怎么能阻止它這樣做呢?

這是一個輸出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);

將Example和SubElement元素上的命名空間設置為與RootElement相同。 它添加了xmlns =“”來清除這些元素的命名空間。

可能是您的root需要正確關閉:

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

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

所以這是我的臟黑客行為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM