2 回答

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
試試這個(gè):
doc
// select all `resources/attr` node
.SelectNodes("resources/attr")
.Cast<XmlNode>()
// that contains the `name` attribute whose value is in `szNodeList`
.Where(x => !string.IsNullOrEmpty(x.Attributes["name"]?.Value) && szNodeList.Contains(x.Attributes["name"].Value))
.ToList()
// and, remove them from their parent
.ForEach(x => x.ParentNode.RemoveChild(x));

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超14個(gè)贊
這里的問題之一是術(shù)語。正如我所理解的,您不是在嘗試刪除屬性- 您是在嘗試根據(jù)屬性的值刪除整個(gè)元素name。
如果您可以為此使用 LINQ to XML,我會(huì)這樣做。它通常使使用 XML 變得更加容易。這是一個(gè)完整的程序來做你想做的事:
using System;
using System.Linq;
using System.Xml.Linq;
class Test
{
static void Main()
{
var namesToRemove = new[]
{
"titleTextColor",
"isLightTheme",
"showText"
};
XDocument doc = XDocument.Load("test.xml");
// For all the elements directly under the document root...
doc.Root.Elements()
// Where the array contains the value of the "name" attribute...
.Where(x => namesToRemove.Contains((string) x.Attribute("name")))
// Remove them from the document
.Remove();
doc.Save("output.xml");
}
}
輸出:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="cropImageStyle" format="reference" />
<attr name="drawerArrowStyle" format="reference" />
<attr name="height" format="dimension" />
<attr name="title" format="string" />
<attr name="navigationMode">
<enum name="listMode" value="1" />
<enum name="normal" value="0" />
<enum name="tabMode" value="2" />
</attr>
</resources>
- 2 回答
- 0 關(guān)注
- 306 瀏覽
添加回答
舉報(bào)