alejandro carnero
alejandro carnero

Reputation: 1784

Reading a value from root node XML

I have this XML : Type A:

 <?xml version="1.0" encoding="UTF-8"?>
 <nfeProc versao="2.00" xmlns="http://www.portalfiscal.inf.br/nfe">
 </nfeProc>

Type B:

<?xml version="1.0" encoding="UTF-8"?>
<cancCTe xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04"> 
</cancCTe>

Type C:

<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
</cteProc> 

I have read the root node with this :

 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.Load(nomear);
 XmlNodeList ml = xmlDoc.GetElementsByTagName("*");
 XmlNode primer = xmlDoc.DocumentElement;
 exti = primer.Name;  

With this code I read nfeProc, cancTE, and cteProc.

How can I read the value of versao?

Upvotes: 4

Views: 1571

Answers (4)

Ilya Ivanov
Ilya Ivanov

Reputation: 23636

As you are using C# 3.5 or later, you can take advantage of LINQ to XML (your tag says you are using C# 4.0, so it certainly applies)

//your xml contents. I've just escaped " symbols, so I can use it as literal
string str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n "+
                 "<nfeProc versao=\"2.00\" xmlns=\"http://www" +
                 ".portalfiscal.inf.br/nfe\">\r\n </nfeProc>";

var xml = XDocument.Parse(str);

Console.WriteLine(xml.Root.Attribute("versao").Value);

prints:

2.00

Upvotes: 3

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32501

Try this

primer.Attributes["versao"].Value

You may also find this helpful:

System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load("PATH TO YOUR .XML");
string value = doc.Element("nfeProc").Attribute("versao").Value;

Upvotes: 0

MikroDel
MikroDel

Reputation: 6735

This is the code:

string attribute = primer.Attributes["versao"].Value;

Upvotes: 0

Related Questions