简体   繁体   中英

Find an delete specific XML node in C#

I need to find the nodes that have the /CFOP/ tag with 5902 as value, so it always end up being all the itens with the tag /det nItem="x"/ with x being always > 1. So what can i do to make it work?

The XML file: https://drive.google.com/file/d/1-ayEd1PSP9rECeyYesx3dTndInlqNouR/view?usp=sharing

My code is opening the file and trying to erase all the nodes "det nItem > 2", here's what i've done from my researches. But it only opens and save the file without any changes.

using System.Xml;

XmlDocument xml = new XmlDocument();
xml.Load(filename: "C:/Users/A376228/Desktop/xml/ped1.xml");
XmlNodeList nodeList = xml.SelectNodes(xpath: "/infNFe/det[@CFOP=" + 5902 + "]");

foreach (XmlNode node in nodeList)
{
    node.ParentNode.RemoveChild(node);
}
xml.Save(filename: "C:/Users/A376228/Desktop/xml/ped1-ready.xml");

Thanks for your time!

Use the XmlNamespaceManager . This code should delete the single node where nItem > 2:

XmlDocument xml = new XmlDocument();
xml.Load(filename: "C:/Users/A376228/Desktop/xml/ped1.xml");
XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xml.NameTable);
xmlNamespaceManager.AddNamespace("x", "http://www.portalfiscal.inf.br/nfe");
XmlNodeList nodeList = xml.DocumentElement.SelectNodes(xpath: "//x:infNFe/x:det[@nItem > 2]",
    xmlNamespaceManager);

foreach (XmlNode node in nodeList)
{
    node.ParentNode.RemoveChild(node);
}
xml.Save(filename: "C:/Users/A376228/Desktop/xml/ped1-ready.xml");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM