简体   繁体   中英

How to get value from XML file

Given the following XML file:

<root>
   <country>
       <name></name>
       <locationOU>null</location>
   </country>
   <country>
       <name>Sweden</name>
       <locationOU>Some Value</locationOU>
   </country>
   <country>
       <name>Lithuania</name>
       <locationOU>Some Value</locationOU>
   </country>
   <country>
       <name>Belgium</name>
       <locationOU>Some Value</locationOU>
   </country>
</root>

How do I get the value of locationOU based on name value eg. name = Sweden ?

You can work with XPath via XPathSelectElement(XNode, String) .

using System.Xml.Linq;
using System.Xml.XPath;

// Read XML file
XDocument root = XDocument.Load(/* Your XML file path */);

// Read XML from string
// XDocument root = XDocument.Parse(xml);

XElement result = root.XPathSelectElement("/root/country[name='Sweden']");
        
string locationOU = result.Element("locationOU").Value;

Demo @ .NET Fiddle

I like using xml linq with a dictionary:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication40
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, string> dict = doc.Descendants("country")
                .GroupBy(x => (string)x.Element("name"), y => (string)y.Element("locationOU"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

            string sweedenLocation = dict["Sweden"];
        }
    }
}
XDocument doc = XDocument.Parse(XML_TEXT);
XElement rootElement = doc.XPathSelectElement("root");
var countries = rootElement?.Descendants().Where(e => e.Name.LocalName.Equals("country"));
var yourCountry = countries.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals("locationOU") && d.Value == "Sweden");

You can use XPath with above answers @Yong Shun

Or You can use DataSet as bellow:

DataSet ds=new DataSet();
ds.readXml(filename);
DataTable dt=ds.Tables[0];
string name="Sweden";
foreach(DataRow dr in dt.Select(String.Format("name='{0}'",name))
{
    string locationOU=dr["locationOU"].toString();
}

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