【问题标题】:c# : merge 2 xelement add automatically empty xmlns attribute to the secondc# : merge 2 xelement 自动将空 xmlns 属性添加到第二个
【发布时间】:2015-09-17 16:48:16
【问题描述】:

我有 2 个要合并的 xelement:

第一个是这样的:

<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

【问题讨论】:

    标签: c# xml-serialization


    【解决方案1】:

    xmlns 定义了一个XML Namespace。它不会对您的应用程序逻辑造成任何问题。

    网络提供了许多可能性:

    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

    From here

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

    3

    From here ,基于接口:

    string RemoveAllNamespaces(string xmlDocument);
    

    我在这里代表用于删除 XML 命名空间的最终干净且通用的 C# 解决方案:

    //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)));
        }
    

    【讨论】:

      猜你喜欢
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多