Home > Enterprise >  How to get value from XML file
How to get value from XML file

Time:09-30

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?

CodePudding user response:

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

CodePudding user response:

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"];
        }
    }
}

CodePudding user response:

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");

CodePudding user response:

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();
}
  • Related