简体   繁体   中英

How to get data from an XML File in C# using XMLDocument class?

Good Evening All, and happy weekend!.

I have been trying all day to understand how to parse my simple XML file so I can understand it enough to write a personal project I want to work on.

I have been reading articles on this site and others but cannot get past where I am :(

My XML Document is ...

<XML>
  <User>
    <ID>123456789</ID>
    <Device>My PC</Device>
  </User>
  <History>
    <CreationTime>27 June 2013</CreationTime>
    <UpdatedTime>29 June 2013</UpdatedTime>
    <LastUsage>30 June 2013</LastUsage>
    <UsageCount>103</UsageCount>
  </History>
  <Configuration>
    <Name>Test Item</Name>
    <Details>READ ME</Details>
    <Enabled>true</Enabled>   
  </Configuration>
</XML>

I am trying to get the value in the details element (READ ME). Below is my code

// Start Logging Progress
Console.WriteLine("Test Application - XML Parsing and Creating");
Console.ReadKey();

// Load XML Document
XmlDocument MyDoc = new XmlDocument();  MyDoc.Load(@"E:\MyXML.XML");

// Select Node
XmlNode MyNode = MyDoc.SelectSingleNode("XML/Configuration/Details");

// Output Node Value
Console.WriteLine(String.Concat("Details: ", MyNode.Value));

// Pause
Console.ReadKey();

My console application is running and outputing "Target: " but not giving me the detail within the element.

Can somebody see why this is happening, and perhaps give me advice if I am completely off the wheel? I have no previous knowledge in reading XML files; hence where I am now :)

Thanks! Tom

With the your XPATH expression

// Select Node
XmlNode MyNode = MyDoc.SelectSingleNode("XML/Configuration/Details");

your are selection an element so the type of the MyNode will be XmlElement but the Value of an XmlElement is always null (see on MSDN ) so you need to use XmlElement.InnerText or XmlElement.InnerXml isntead.

So the changed your code to

// Output Node Value
Console.WriteLine(String.Concat("Details: ", MyNode.InnerText));

Or you can select the content of an element with using the XPATH text() function, in this case MyNode will be XmlText where you get its value with Value :

// Select Node
XmlNode MyNode = MyDoc.SelectSingleNode("XML/Configuration/Details/text()");

// Output Node Value
Console.WriteLine(String.Concat("Details: ", MyNode.Value));

As a sidenote if you are anyway learning XML manipulation in C# you should check out LINQ to XML which is another/newer way to working with XML in C#.

Just for interest, a little-known "simple" syntax is this:

XmlDocument myDoc = new XmlDocument();
myDoc.Load(@"D:\MyXML.XML");

string details = myDoc["XML"]["Configuration"]["Details"].InnerText;

Note that this (and the XPath approach) could go pop if your XML doesn't conform to the structure you're expecting, so you'd ideally put some validation in there as well.

U can use Xpath library for that (u must include "System.Xml.XPath"):

 XmlDocument document = new XmlDocument();
         document.Load("MyXml.xml");
         XPathNavigator navigator = document.CreateNavigator();

        foreach (XPathNavigator nav in navigator.Select("//Details"))
         {
             Console.WriteLine(nav.Value);

        }

the above code iterate over every node called (Details) extracting information and print it.

If you want to retrieve a particular value from an XML file

 XmlDocument _LocalInfo_Xml = new XmlDocument();
            _LocalInfo_Xml.Load(fileName);
            XmlElement _XmlElement;
            _XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
            string Value = _XmlElement.InnerText;

Value contains the text 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