C# 如何查找XML的节点并将其删除
我有一个这样的xmlC# 如何查找XML的节点并将其删除,c#,asp.net,xml,C#,Asp.net,Xml,我有一个这样的xml <Order> <OrderSections> <OrderSection type="1" name="S 1" id="3"> <ShippingAmount>15.02</ShippingAmount> </OrderSection> <OrderSection type="1" name="S 2" id="4">
<Order>
<OrderSections>
<OrderSection type="1" name="S 1" id="3">
<ShippingAmount>15.02</ShippingAmount>
</OrderSection>
<OrderSection type="1" name="S 2" id="4">
<ShippingAmount>0</ShippingAmount>
</OrderSection>
</OrderSections>
</Order>
15.02
0
如何找到id=4的order部分并将其从XmlDocument中删除?我正在查看,但这是不同的,因为正在搜索的值属于类似于
<players>
<player>
<name>User2</name>
</player>
</players>
用户2
但是我的XML在
属性值中有id。您可以使用Linq to XML:
var xdoc = XDocument.Load(path_to_xml);
xdoc.Descendants("OrderSection")
.Where(os => (int)os.Attribute("id") == 3)
.Remove();
xdoc.Save(path_to_xml);
您可以使用Linq转换为Xml:
var xdoc = XDocument.Load(path_to_xml);
xdoc.Descendants("OrderSection")
.Where(os => (int)os.Attribute("id") == 3)
.Remove();
xdoc.Save(path_to_xml);
您需要对属性使用
@
:
XmlNode node = doc.SelectSingleNode("/Order/OrderSections/OrderSection[@id='4']");
node.ParentNode.RemoveChild(node);
查看您需要为属性使用的
@
:
XmlNode node = doc.SelectSingleNode("/Order/OrderSections/OrderSection[@id='4']");
node.ParentNode.RemoveChild(node);
看一下使用XmlDocument类和xpath查找元素
string path = "orders.xml";
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(path);
foreach (XmlNode entry in XMLDoc.SelectNodes("//OrderSection[@id='4']"))
{
entry.ParentNode.RemoveChild(entry);
}
使用XmlDocument类和xpath查找元素
string path = "orders.xml";
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(path);
foreach (XmlNode entry in XMLDoc.SelectNodes("//OrderSection[@id='4']"))
{
entry.ParentNode.RemoveChild(entry);
}