How can I read an XML attribute using C#'s XmlDocument?
I have an XML file which looks somewhat like this:
<?xml version="1.0" encoding="utf-8" ?> <MyConfiguration xmlns="http://tempuri.org/myOwnSchema.xsd" SuperNumber="1" SuperString="whipcream"> <Other stuff /> </MyConfiguration>
How would I read the XML attributes SuperNumber and SuperString?
Currently I'm using XmlDocument, and I get the values in between using XmlDocument's GetElementsByTagName()
and that works really well. I just can't figure out how to get the attributes?
If you load the XML into an XmlDocument , there are any number of ways to get the attribute's value. You could use XPath to find the attribute: XmlAttribute a = doc. SelectSingleNode("/reply/@success"); Console.
If all you need to do is view the data in an XML file, you're in luck. Just about every browser can open an XML file. In Chrome, just open a new tab and drag the XML file over. Alternatively, right click on the XML file and hover over "Open with" then click "Chrome".
The XmlDocument class is an in-memory representation of an XML document. It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. DOM stands for document object model. To read more about it, see XML Document Object Model (DOM).
XmlDocument can't be disposed because it does not implement IDisposable.
XmlNodeList elemList = doc.GetElementsByTagName(...); for (int i = 0; i < elemList.Count; i++) { string attrVal = elemList[i].Attributes["SuperString"].Value; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With