1

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 the xml file trough C#?

Ivar
  • 6,138
  • 12
  • 49
  • 61

3 Answers3

2

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();
jing
  • 1,919
  • 2
  • 20
  • 39
1

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);
      }
cordellcp3
  • 3,557
  • 1
  • 17
  • 14
0

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.

gideon
  • 19,329
  • 11
  • 72
  • 113
  • I'm using C# 3.0, so I can't use linq. – Ivar Mar 18 '11 at 11:26
  • Yes you can [C# 3.0](http://en.wikipedia.org/wiki/C_Sharp_3.0#LINQ_.28Language-Integrated_Query.29) See also this: http://stackoverflow.com/questions/247621/what-are-the-correct-version-numbers-for-c – gideon Mar 18 '11 at 12:43
  • Forgive me for being a newb, but I can't get the XElement. Neither I can find the System.Xml.Linq reference. :( – Ivar Mar 18 '11 at 13:20
  • I meant I'm using .NET 3.0, not C# 3.0. (Honestly I though it was the same :$) – Ivar Mar 18 '11 at 13:27
  • @Ivar no problem. I knew you would get the answer eventually. There is also an [XmlDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx) class that is part of .net 2.0 But its more verbose to use. – gideon Mar 18 '11 at 14:01