Access xml files from a directory c#

Asked

Viewed 67 times

2

I have a function that receives an xml file as a parameter.

  public void lerXML(XmlDocument xmlDoc)
    {
        XmlNodeList xnCNPJ = xmlDoc.GetElementsByTagName("emit");
        XmlNodeList xnNFE = xmlDoc.GetElementsByTagName("ide");
        XmlNodeList xnChaveNFE = xmlDoc.GetElementsByTagName("infProt");
        ...
    }

I want to apply this function to all files in a directory

In case, I’m doing so:

 System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Diretorio);

            foreach (FileInfo a in dirInfo.GetFiles())
            {
                lerXML(a.FullName);
            }

However, the following error appears:

"Unable to convert from string to System.xml.Xmldocument"

I tried to leave it like this: lerXML(a); but same mistake.

How could I accomplish this conversion?

  • Consider using XDocument instead of XMLDocument.

  • what would be the difference between the two?

  • XDocument is much simpler to use and manipulate. It also has no flaw in the validation process (XSD) where in case of validation errors the XMLDocument does not allow searching for the element or attribute that caused the validation error (although this facility has been documented in practice has not been implemented).

1 answer

1


You need to upload the file since your method expects one XmlDocument... when you do that lerXML(a.FullName), is passing a string and not a representation of the document.

System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(Diretorio);
foreach (FileInfo a in dirInfo.GetFiles())
{
    var documentoXml = new XmlDocument();
        documentoXml.Load(a.FullName);                

        lerXML(documentoXml);
}
  • That’s right, it worked right, thank you hehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.