开发者

How to get an XML value out of another XML value at C#

I need to get a value out of an XML file...

I have this XML file for example:

<?xml version="1.0"?>
<hwids>
<user>
    <userName>Ivar</userName>
    <hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>
</user>
<user>
    <userName>Jerremy</userName>
    <hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>
</user>
</hwids>

Now, if I have the value BFEB-FBFF-0000-06FD-C87C-FA30, how do I get the name Ivar, out of开发者_StackOverflow社区 the xml file trough C#?


I used in my application something like this:

using System.Data;

DataSet dataSet = new DataSet();
dataSet.ReadXml(xmlFullPath, XmlReadMode.Auto);
DataRow[] dataRows = dataSet.Tables["user"].Select("hwid like 'BFEB-FBFF-0000-06FD-C87C-FA30'");
if (dataRows.Length == 0)
    return;
string sUser = dataRows[0]["userName"].ToString();


you can accomplish this also with XmlDocument of the System.Xml namespace, which is supported in .NET 3.0

var xml = "<?xml version=\"1.0\"?>" +
      "<hwids> " + "<user>" +
      "<userName>Ivar</userName>" +
      "<hwid>BFEB-FBFF-0000-06FD-C87C-FA30</hwid>"+
      "</user> " +
      "<user>" +
      "<userName>Jerremy</userName>" +
      "<hwid>BFE9-FBFF-0000-06E8-E41E-5034</hwid>" +
      "</user>" +
      "</hwids>";

      XmlDocument doc = new XmlDocument();
      doc.LoadXml(xml);
      var ret = doc.GetElementsByTagName("userName");

      for (int i = 0; i < ret.Count; i++)
      {
           Debug.WriteLine(ret.Item(i).InnerText);
      }


I think this should work:

XElement root = XElement.Load("file.xml");
IEnumerable<XElement> hws =
    from el in root.Elements("user")
    where (string)el.Element("userName") == "Ivar"
    select el.Descendant("hwid);

Haven't tested it out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜