我有一个XML,它有一个节点,使用C#在文件的多个级别上重复。
XML示例:
<books>
<book>
<title>The Walking Dead</title>
<author>Test Name</author>
<isbn>1239859895</isbn>
</book>
<book>
<title>The Walking Dead</title>
<author>
<isbn>29893893893</isbn>
<firstname>test1</firstname>
<lastname>test</lastname>
</author>
</book>
</books>
我想从此XML文档中删除所有 isbn 节点,而不管其位置如何。
答案 0 :(得分:1)
最简单的方法是使用XDocument而不是XmlDocument。使用.Descendants()查找特定名称/类型的所有节点。然后。删除()他们。
string xml = @"<books>
<book>
<title>The Walking Dead</title>
<author>Test Name</author>
<isbn>1239859895</isbn>
</book>
<book>
<title>The Walking Dead</title>
<author>
<isbn>29893893893</isbn>
<firstname>test1</firstname>
<lastname>test</lastname>
</author>
</book>
</books>";
XDocument xdoc = XDocument.Parse(xml);
xdoc.Descendants("isbn").Remove();
string result = xdoc.ToString();
但是如果你想使用XmlDocument,请使用以下代码:
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
foreach (var node in new List<XmlNode>(xmldoc.GetElementsByTagName("isbn")
.OfType<XmlNode>()).Where(
x => x.ParentNode != null))
{
node.ParentNode.RemoveChild(node);
}
string result = xmldoc.OuterXml;
答案 1 :(得分:0)
如您所说,您正在使用XmlDocument
,则需要通过父节点上的RemoveChild
方法删除子XmlElement
节点:
string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<books>
<book>
<title>The Walking Dead</title>
<author>Test Name</author>
<isbn>1239859895</isbn>
</book>
<book>
<title>The Walking Dead</title>
<author>
<isbn>29893893893</isbn>
<firstname>test1</firstname>
<lastname>test</lastname>
</author>
</book>
</books>
";
// Initialize and load the XmlDocument
var doc = new XmlDocument();
doc.LoadXml(xml);
// Delete all XmlElements named "isbn".
var list = doc.DocumentElement.GetElementsByTagName("isbn").OfType<XmlElement>().ToArray();
foreach (var element in list)
{
var parent = element.ParentNode;
if (parent != null)
parent.RemoveChild(element);
}
var newXml = doc.OuterXml;
Debug.WriteLine(newXml);
输出是:
<?xml version="1.0" encoding="utf-16"?>
<books>
<book>
<title>The Walking Dead</title>
<author>Test Name</author>
</book>
<book>
<title>The Walking Dead</title>
<author>
<firstname>test1</firstname>
<lastname>test</lastname>
</author>
</book>
</books>