基于属性删除XDocument节点的问题
本文关键字:XDocument 节点 问题 删除 于属性 属性 | 更新日期: 2023-09-27 18:05:34
我正试图根据其name
属性删除XDocument
中称为doc
的CreditCard
节点,但其未按预期工作。
doc
是我的XDocument
,它看起来像这样:
XDocument doc = new XDocument(
new XComment("XML test file"),
new XElement("CreditCards",
new XElement("CreditCard",
new XAttribute("Name", "TestCard1"),
new XAttribute("phoneNumber", 121212142121)),
new XElement("CreditCard",
new XAttribute("Name", "TestCard2"),
new XAttribute("phoneNumber", 6541465561)),
new XElement("CreditCard",
new XAttribute("Name", "TestCard3"),
new XAttribute("phoneNumber", 445588))
)
);
这是我试图运行的查询,但它没有删除节点。name
是一个字符串,我传递给这个函数作为引用,告诉它删除什么
var q = from node in doc.Descendants("CreditCards")
let attr = node.Attribute("name")
where attr != null && attr.Value == name
select node;
q.ToList().ForEach(x => x.Remove());
我没有得到任何错误,但也没有删除任何东西
您的代码正在查找信用卡"信用卡
试试下面的;
doc.Descendants("CreditCard")
.Where(x => (string)x.Attribute("Name") == name)
.Remove();
您在查询name
中使用了属性的小写名称。但在你的xml属性的名称是Name
。Xml区分大小写。另外,属性Name
是CreditCard
元素的子元素,而不是CreditCards
元素的子元素:
doc.Descendants("CreditCards")
.Elements()
.Where(c => (string)c.Attribute("Name") == name)
.Remove();