Reading 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 read the root of the node as follows:

  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 meaning of versao ?

+4
source share
4 answers

When you use C # 3.5 or later , you can use LINQ to XML (your tag says you are using C # 4.0, so it really 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 
+3
source

try it

 primer.Attributes["versao"].Value 

You may also find this useful:

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

This is the code:

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

All Articles