删除所有具有给定名称的 XML 属性 [英] Remove all XML Attributes with a Given Name
问题描述
我正在编辑一系列 XML 文件,我需要删除名称为foo"的所有属性.此属性出现在不止一种类型的元素中.XML 中的一个示例片段可能是:
I am editing a series of XML files, and I need to remove all attributes with the name "foo". This attribute appears in more than one type of element. An example snippet from the XML might be:
<bodymatter id="######">
<level1 id="######">
<pagenum page="#####" id="######" foo="######" />
<h1 id="#####" foo="#####">Header</h1>
<imggroup id="#######">
.
.
etc.
我最好的解决方案是使用正则表达式:
The best solution I have uses Regex:
Regex regex = new Regex("foo=\"" + ".*?" + "\"", RegexOptions.Singleline);
content = regex.Replace(content, "");
我知道内置 XML 解析器会有所帮助,但理想情况下,我想进行简单的 XML 替换/删除,而不必处理整个 XML 解析器的负担.在这种情况下,Regex 是最佳解决方案吗?
I know built-in XML parsers could help, but ideally I want to make simple XML replacements/removals without having to deal with the baggage of an entire XML parser. Is Regex the best solution in this case?
编辑:
在 XmlDocument 类中进行一些研究后,这是我想出的一种可能的解决方案(删除存储在数组ids"中的多个属性类型):
After some research in the XmlDocument class, here is one possible solution I came up with (to remove more than one attribute type stored in the array "ids"):
private void removeAttributesbyName(string[] ids)
{
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList xnlNodes = doc.GetElementsByTagName("*");
foreach (XmlElement el in xnlNodes)
{
for (int i = 0; i <= ids.Length - 1; i++)
{
if (el.HasAttribute(ids[i]))
{
el.RemoveAttribute(ids[i]);
}
if (el.HasChildNodes)
{
foreach (XmlNode child in el.ChildNodes)
{
if (child is XmlElement && (child as XmlElement).HasAttribute(ids[i]))
{
(child as XmlElement).RemoveAttribute(ids[i]);
}
}
}
}
}
}
我不知道这是否尽可能有效,但我已经对其进行了测试,它似乎工作正常.
I don't know if this is as efficient as it possibly could be, but I've tested it and it seems to work fine.
推荐答案
不要将正则表达式用于 XML 操作.您可以使用 Linq to XML:
Do not use regex for XML manipulation. You can use Linq to XML:
XDocument xdoc = XDocument.Parse(xml);
foreach (var node in xdoc.Descendants().Where(e => e.Attribute("foo")!=null))
{
node.Attribute("foo").Remove();
}
string result = xdoc.ToString();
这篇关于删除所有具有给定名称的 XML 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!