Gabriel Zilioti
Gabriel Zilioti

Reputation: 3

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!

Upvotes: 0

Views: 175

Answers (1)

mm8
mm8

Reputation: 169270

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");

Upvotes: 1

Related Questions