从XML中删除指定命名空间中的所有节点
本文关键字:命名空间 节点 XML 删除 | 更新日期: 2023-09-27 17:59:25
我有一个XML文档,它在名称空间中包含一些内容。这里有一个例子:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:test="urn:my-test-urn">
<Item name="Item one">
<test:AlternativeName>Another name</test:AlternativeName>
<Price test:Currency="GBP">124.00</Price>
</Item>
</root>
我想删除test
名称空间中的所有内容——不仅从标记中删除名称空间前缀,而且实际上从文档中(在本例中)test
名称空间中删除所有节点(元素和属性)。我需要的输出是:
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:test="urn:my-test-urn">
<Item name="Item one">
<Price>124.00</Price>
</Item>
</root>
我目前并不太担心命名空间声明是否仍然存在,目前我很乐意只删除指定命名空间中的内容。请注意,文档中可能有多个要修改的名称空间,因此我希望能够指定要删除内容的名称空间。
我尝试过使用.Descendants().Where(e => e.Name.Namespace == "test")
进行查询,但这只是为了返回IEnumerable<XElement>
,所以它对我查找属性没有帮助,如果我使用.DescendantNodes()
,我看不到查询命名空间前缀的方法,因为这似乎不是XNode上的属性。
我可以遍历每个元素,然后遍历元素上的每个属性,检查每个元素的Name.Namespace
,但这似乎很不雅,很难阅读。
有没有一种方法可以使用LINQ to Xml实现这一点?
遍历元素然后遍历属性似乎不太难阅读:
var xml = @"<?xml version='1.0' encoding='UTF-8'?>
<root xmlns:test='urn:my-test-urn'>
<Item name='Item one'>
<test:AlternativeName>Another name</test:AlternativeName>
<Price test:Currency='GBP'>124.00</Price>
</Item>
</root>";
var doc = XDocument.Parse(xml);
XNamespace test = "urn:my-test-urn";
//get all elements in specific namespace and remove
doc.Descendants()
.Where(o => o.Name.Namespace == test)
.Remove();
//get all attributes in specific namespace and remove
doc.Descendants()
.Attributes()
.Where(o => o.Name.Namespace == test)
.Remove();
//print result
Console.WriteLine(doc.ToString());
输出:
<root xmlns:test="urn:my-test-urn">
<Item name="Item one">
<Price>124.00</Price>
</Item>
</root>
尝试一下。我必须从根元素中提取名称空间,然后运行两个独立的Linqs:
- 删除具有命名空间的元素
- 删除具有命名空间的属性
代码:
string xml = "<?xml version='"1.0'" encoding='"UTF-8'"?>" +
"<root xmlns:test='"urn:my-test-urn'">" +
"<Item name='"Item one'">" +
"<test:AlternativeName>Another name</test:AlternativeName>" +
"<Price test:Currency='"GBP'">124.00</Price>" +
"</Item>" +
"</root>";
XDocument xDocument = XDocument.Parse(xml);
if (xDocument.Root != null)
{
string namespaceValue = xDocument.Root.Attributes().Where(a => a.IsNamespaceDeclaration).FirstOrDefault().Value;
// Removes elements with the namespace
xDocument.Root.Descendants().Where(d => d.Name.Namespace == namespaceValue).Remove();
// Removes attributes with the namespace
xDocument.Root.Descendants().ToList().ForEach(d => d.Attributes().Where(a => a.Name.Namespace == namespaceValue).Remove());
Console.WriteLine(xDocument.ToString());
}
结果:
<root xmlns:test="urn:my-test-urn">
<Item name="Item one">
<Price>124.00</Price>
</Item>
</root>
如果您想从根元素中删除名称空间,请在获得namespaceValue 后在If语句中添加此行
xDocument.Root.Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
结果:
<root>
<Item name="Item one">
<Price>124.00</Price>
</Item>
</root>