簡體   English   中英

c#:合並2 xelement自動添加空xmlns屬性到第二個

[英]c# : merge 2 xelement add automatically empty xmlns attribute to the second

我有兩個要合並的元素:

第一個是這樣的:

<element xmlns="test1">
    <child>element child</child>
</element>

第二個是這樣的:

<element2>
    <child2>element2 child2</child2>
</element2>

我想獲得以下內容:

<root xmlns="fusion">   
    <element xmlns="test1">
        <child>element child</child>
    </element>
    <element2>
        <child2>element2 child2</child2>
    </element2>
</root> 

問題是,當我嘗試在根節點中合並2個xelement時,它會自動向我不需要的第二個元素添加一個空的xmlns屬性:

<root xmlns="fusion">   
    <element xmlns="test1">
        <child>element child</child>
    </element>
    <element2 xmlns="">
        <child2>element2 child2</child2>
    </element2>
</root> 

這是我的代碼:

        XNamespace defaultNs = "fusion";
        var root = new XElement(defaultNs + "root");

        root.Add(element);
        root.Add(element2); //when I debug and visualize my element2 I don't have this empty xmlns attribute, it's only when I do the fusion that it appears

xmlns定義一個XML命名空間 它不會對您的應用邏輯造成任何問題。

網絡隔離器有許多可能的功能:

1個

您正在將名稱空間為""的元素添加到名稱空間為"http://schemas.microsoft.com/developer/msbuild/2003"的元素中。 這意味着新元素需要xmlns屬性。

如果添加帶有名稱空間"http://schemas.microsoft.com/developer/msbuild/2003"的元素,則不需要xmlns屬性(因為它是從父元素繼承的):

var n = xDoc.CreateNode(XmlNodeType.Element, "Compile",
            "http://schemas.microsoft.com/developer/msbuild/2003");

2

從這里

foreach (XElement e in root.DescendantsAndSelf())
{
    if (e.Name.Namespace == string.Empty)
    {
        e.Name = ns + e.Name.LocalName;
    }
}

3

從這里開始 ,基於界面:

string RemoveAllNamespaces(string xmlDocument);

我在這里代表最終的干凈通用的C#解決方案,用於刪除XML名稱空間:

//Implemented based on interface, not part of algorithm
public static string RemoveAllNamespaces(string xmlDocument)
{
    XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

    return xmlDocumentWithoutNs.ToString();
}

//Core recursion function
 private static XElement RemoveAllNamespaces(XElement xmlDocument)
    {
        if (!xmlDocument.HasElements)
        {
            XElement xElement = new XElement(xmlDocument.Name.LocalName);
            xElement.Value = xmlDocument.Value;

            foreach (XAttribute attribute in xmlDocument.Attributes())
                xElement.Add(attribute);

            return xElement;
        }
        return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
    }

暫無
暫無

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

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