简体   繁体   中英

get the value of a xml tag

In below xml, I want to fetch the value of tag ID where name tag have value 'HighLevelReport%'.

<RunResults xmlns="http://www.hp.com/PC/REST/API">
  <RunResult>
    <ID>17245</ID>
    <Name>output.mdb.zip</Name>
    <Type>Output Log</Type>
    <RunID>4196</RunID>
  </RunResult>
  <RunResult>
    <ID>17246</ID>
    <Name>VuserLog.zip</Name>
    <Type>Output Log</Type>
    <RunID>4196</RunID>
  </RunResult>                            
  <RunResult>
    <ID>17248</ID>
    <Name>Reports.zip</Name>
    <Type>HTML Report</Type>
    <RunID>4196</RunID>
  </RunResult>
  <RunResult>
    <ID>17249</ID>
    <Name>HighLevelReport_4196.xls</Name>
    <Type>Rich Report</Type>
    <RunID>4196</RunID>
  </RunResult>                          
</RunResults>

currently I am using dataset to get the value

using (DataSet reader = ds.ReadXml(xml))
{                               
    DataRow[] DR = reader.Tables[0].Select("Name like '%HighLevelReport%'");
    int testID = Convert.ToInt32(DR[0].ItemArray[0].ToString());
}

Please help me with some other option of doing same.

I would avoid using a DataSet unless you really, really need to. If you're just dealing with XML, use an XML API. I find LINQ to XML the best for this. For example:

XNamespace ns = "http://www.hp.com/PC/REST/API";
var doc = XDocument.Parse(xml);
var ids = doc.Root
             .Elements(ns + "RunResult")
             .Where(rr => ((string) rr.Element(ns + "Name"))?.StartsWith("HighLevelReport") ?? false)
             .Select(rr => (string) rr.Element(ns + "RunID"));

Here's a complete example:

using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        // Alternatively, use XDocument.Load to load from a file
        string xml = File.ReadAllText("test.xml");
        var doc = XDocument.Parse(xml);
        XNamespace ns = "http://www.hp.com/PC/REST/API";
        var ids = doc.Root
            .Elements(ns + "RunResult")
            .Where(rr => ((string) rr.Element(ns + "Name"))?.StartsWith("HighLevelReport") ?? false)
            .Select(rr => (string) rr.Element(ns + "RunID"));
        foreach (var id in ids)
        {
            Console.WriteLine(id);
        }
    }
}

The Where clause here handles the Name element being missing - the cast to string would return null, and so StartsWith wouldn't be called. If the RunID element is missing, you'll end up with a null element in your output.

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