简体   繁体   中英

Reading attribute from an XML file

I have an XML file which looks like this

<SendInvoiceResult xmlns="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" IsSucceded="true">
  <Value Id="123456" Number="1" InvoiceScenario="Scenario" /> 
</SendInvoiceResult>

I'm trying to read the attributes of this file but so far all my tries based on other questions on Stackoverflow either returned null or "Object reference not set to an instance of an object" error.

My latest try is this:

var testXml = new XmlDocument();
testXml.LoadXml(test);

var node = testXml.SelectSingleNode("/SendInvoiceResult/Value");
var id = node.Attributes["Id"].Value;

This approach returns "Object reference not set to an instance of an object" too. I'm wondering if something is wrong with the way XML is structures at this point.

I'm open to new methods and suggestions of course, all I need is to read the values of attributes in this and other similar XML files.

Use XDocument. It is much more modern and capable.

var doc = XElement.Load(test);
var id = doc.Root.Element("Value").Attribute("Id").Value;

You must define xml namespace.

var doc = new XmlDocument();
doc.Load("test.txt");

var manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("ns", "http://tempuri.org/");

var node = doc.SelectSingleNode("/ns:SendInvoiceResult/ns:Value", manager);
var id = node.Attributes["Id"].Value;

Console.WriteLine(id);

Better use modern and more convenient linq to xml.

using System.Xml.Linq;

var doc = XDocument.Load("test.txt");
XNamespace ns = "http://tempuri.org/";
var id = doc.Root.Element(ns + "Value").Attribute("Id").Value;
Console.WriteLine(id);

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