简体   繁体   中英

Extract Attribute name from XML File, given the ParentNode's Attribute Value in C#

Given the following XML File,

    - <CommandTiming Name="Architecture.Dome">
      <Sample Name="run1" EllapsedTime="627" /> 
      <Sample Name="run2" EllapsedTime="636" /> 
      <Sample Name="run3" EllapsedTime="650" /> 
      <Sample Name="run4" EllapsedTime="626" /> 
      <Sample Name="run5" EllapsedTime="643" /> 
      </CommandTiming>

I would like to extract the EllapsedTime for run1, run2, run3, run4 and run5, given the CommandTiming Name = "Architecture.Dome"

I want an array with the values 627, 636, 650, 626, 643.

Thanks.

This should do it:

XDocument doc = XDocument.Parse(
 "<CommandTiming Name='Architecture.Dome'>" + 
        "<Sample Name='run1' EllapsedTime='627' />" +
        "<Sample Name='run2' EllapsedTime='636' /></CommandTiming>");
var values = doc.XPathSelectElements("CommandTiming[@Name='Architecture.Dome']/Sample")
    .Select(v => v.Attribute("EllapsedTime").Value);

Live example: http://rextester.com/rundotnet?code=CNN24938

Try something like this:

XDocument doc = XDocument.Parse(
 "<CommandTiming Name='Architecture.Dome'>" + 
        "<Sample Name='run1' EllapsedTime='627' />" +
        "<Sample Name='run2' EllapsedTime='636' /></CommandTiming>");//etc    
var elapsedTimes = doc.Root.Elements().Attributes("EllapsedTime").
    Select(e => e.Value).ToArray<string>();

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