ERROR - Paste XElement C #

2

Hello. I'm trying to get a Node from an xml NFe and this may be showing up the image error.

Atthebeginningoftheclass,aprivateXDocumentxDoc;variablewascreated.Thexmlfileisinsidethedebugfolder.

EvenputtingsothesameErrorappears:

XElement_xDetModelo=newXElement(xDoc.Element("nfeProc").Element("NFe").Element("infNFe").Element("det"));

Below is part of the XML code I'm trying to get:

<?xml version="1.0" encoding="UTF-8"?>
<nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" versao="3.10">
    <NFe xmlns="http://www.portalfiscal.inf.br/nfe">
        <infNFe Id="NFeXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" versao="3.10">
            <ide>
                    ...
            </ide>
            <emit>
                    ...
            </emit>
            <dest>
                    ...
            </dest>
            <det nItem="1">
                <prod>
                    ...
    
asked by anonymous 19.09.2016 / 22:15

2 answers

1

The file has namespace , and at the time of the elements search it needs to be informed:

XNamespace nameSpace = "http://www.portalfiscal.inf.br/nfe";
string xml = System.IO.File.ReadAllText("doc.xml");

XDocument xDoc = XDocument.Parse(xml);
XElement element = xDoc.Element(nameSpace + "nfeProc")
          .Element(nameSpace + "NFe")
          .Element(nameSpace + "infNFe")
          .Element(nameSpace + "det");

Example on SOen , demonstrate this.

Edited:

Func<string, XName> item = delegate(string value)
{
    XNamespace nameSpace = "http://www.portalfiscal.inf.br/nfe";
    return nameSpace + value;
};


string xml = System.IO.File.ReadAllText("doc.xml");

XDocument xDoc = XDocument.Parse(xml);           

var element = from el in xDoc.Element(item("nfeProc"))
        .Element(item("NFe"))
        .Element(item("infNFe"))
        .Element(item("det"));
    
19.09.2016 / 22:50
3

Although you have already resolved with the response of colleague Virgilio Novic I will show you another way to do this, you can create the classes related to NFe.

It may be useful for you or someone else who is reading.

There is an application called xsd.exe . Summarizing roughly, it takes the schema and returns a class.

You should drop the NFe schemas and save them to some folder.

Do the following as in the image below:

Logically replace the path according to where you saved the NFe schema.

Within the folder of xsd.exe it will create a file .cs as in the image below:

Afteryouaddtheclasstoyourproject,youcanuseNFeasanobject.

Complementing:

You can place this block of code inside a try\catch , so if the xml is not valid, an exception is thrown. Since you generated the class from the schema, only valid xml's will be deserialized, this will save you a lot of headaches.

    
19.09.2016 / 23:10