[英]How to get value from XML file
給定以下 XML 文件:
<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>
如何根據名稱值獲取locationOU
的值,例如。 name = Sweden
?
您可以通過XPathSelectElement XPathSelectElement(XNode, String)
使用 XPath。
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;
我喜歡將 xml linq 與字典一起使用:
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");
上面的答案可以用XPath @Yong Shun
或者您可以使用 DataSet 如下:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.