如何从XML中按属性删除特定节点?

时间:2022-07-28 14:00:56

I am novice and struggling in some XML operations Like open and Delete. I have done the Add part.

我是新手,在一些XML操作中挣扎,比如open和Delete。我已经完成了添加部分。

Partys.xml

Partys.xml

<?xml version="1.0" encoding="utf-8"?>
<Partys>
  <Customers>
    <Customer CustomerID="1">
      <PersonalName>
        <LastName>Baker</LastName>
        <FirstName>Eugene</FirstName>
      </PersonalName>
      <Citizenship>Africa</Citizenship>
    </Customer>
    <Customer CustomerID="2">
      <PersonalName>
        <LastName>Baker</LastName>
        <FirstName>Eugene</FirstName>
      </PersonalName>
      <Citizenship>Africa</Citizenship>
    </Customer>
  </Customers>
 </Partys>

Q: I want to open the node detail customer where CustomerID (Attribute) is 1. What is the C# code for this?

问:我想打开CustomerID(属性)为1的节点细节客户。c#代码是什么?

Q: I want to delete the node customer where CustomerID (Attribute) is 2. What is the C# code for this?

问:我想删除id(属性)为2的节点客户。c#代码是什么?

1 个解决方案

#1


7  

You could try something like this:

你可以试试这样的方法:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Parties.xml");
XmlNode t = xmlDoc.SelectSingleNode("/Partys/Customers/Customer[@CustomerID='2']");
t.ParentNode.RemoveChild(t);
xmlDoc.Save();

Once you have t, you can do whatever you want with it including show it in the Console (by accessing the various properties)

一旦你有了t,你可以用它做任何你想做的事,包括在控制台中显示它(通过访问各种属性)

Here, we have deleted the node and saved back to file, but you could do whatever you want with the XmlDocument....

在这里,我们已经删除的节点并保存文件,但是你可以做任何你想做的事与XmlDocument ....

#1


7  

You could try something like this:

你可以试试这样的方法:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Parties.xml");
XmlNode t = xmlDoc.SelectSingleNode("/Partys/Customers/Customer[@CustomerID='2']");
t.ParentNode.RemoveChild(t);
xmlDoc.Save();

Once you have t, you can do whatever you want with it including show it in the Console (by accessing the various properties)

一旦你有了t,你可以用它做任何你想做的事,包括在控制台中显示它(通过访问各种属性)

Here, we have deleted the node and saved back to file, but you could do whatever you want with the XmlDocument....

在这里,我们已经删除的节点并保存文件,但是你可以做任何你想做的事与XmlDocument ....