简体   繁体   中英

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 ?

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

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;

这是代码:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM