简体   繁体   中英

Get xml node using c#

I have a request that returns a large xml file. I have the file in a XmlDocument type in my application. From that Doc how can I read an element like this:

<gphoto:videostatus>final</gphoto:videostatus>

I would like to pull that value final from that element. Also If i have multiple elements as well, can I pull that into a list? thanks for any advice.

If you already have an XmlDocument then you can use the function GetElementsByTagName() to create an XmlNodeList that can be accessed similar to an array.

http://msdn.microsoft.com/en-us/library/dc0c9ekk.aspx

//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");

//Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");
for (int i=0; i < elemList.Count; i++)
{   
  Console.WriteLine(elemList[i].InnerXml);
} 

You can select nodes using XPath and SelectSingleNode SelectNodes. Look at http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C for examples. Then you can use for example InnerText to get final. Maybe you need to work with namespaces (gphoto). The //videostatus would select all videostatus elements

You can try using LINQ

        XNamespace ns = XNamespace.Get(""); //use the xmnls namespace here
        XElement element = XElement.Load(""); // xml file path
        var result = element.Descendants(ns + "videostatus")
                     .Select(o =>o.Value).ToList();

       foreach(var values in value)
       {

       }           

Thanks

Deepu

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