[英]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命名空间 。 它不会对您的应用逻辑造成任何问题。
网络隔离器有许多可能的功能:
您正在将名称空间为""
的元素添加到名称空间为"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");
foreach (XElement e in root.DescendantsAndSelf())
{
if (e.Name.Namespace == string.Empty)
{
e.Name = ns + e.Name.LocalName;
}
}
从这里开始 ,基于界面:
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.