简体   繁体   中英

C# loop through xml to get innertext value of a specific subnode

I have XML document look like this:

<Runs>
 <Run>
  <LotInfo>
   <Column name="Entity">HST123,</Column> 
   <Column name="Product">XXX123</Column> 
   <Column name="WSOp">1234</Column> 
   <Column name="Route">V234</Column> 
   <Column name="Recipe" /> 
   <Column name="LotNumber">K898722</Column> 
   <Column name="RunStartTime">2014-05-20T17:43:11.8872105</Column> 
  </LotInfo>
  <Operations>
   <Operation type="INTRODUCTION">
   <Column name="Size">1490</Column> 
   <Column name="TimeStamp">2014-05-20T17:43:11.8872105</Column> 
   <Column name="Operator">nismail9</Column> 
   <Column name="Description">
    <![CDATA[ Unknown ]]> 
   </Column>
  <Column name="Status">Success</Column> 
  </Operation>
  <Operation type="RNUCHECK">
   <Column name="Size">1490</Column> 
   <Column name="TimeStamp">2014-05-20T17:43:15.3091731</Column> 
   <Column name="Operator">nismail9</Column> 
   <Column name="Description">
    <![CDATA[ ]]> 
   </Column>
   <Column name="Status">True</Column> 
  </Operation>
  <Operations>
   <Operation type="INTRODUCTION">
   <Column name="Size">1490</Column> 
   <Column name="TimeStamp">2014-05-20T17:58:47.0830259</Column> 
   <Column name="Operator">nismail9</Column> 
   <Column name="Description">
    <![CDATA[ Unknown ]]> 
   </Column>
   <Column name="Status">Success</Column> 
   </Operation>
  </Operations>
 </Run>
</Runs>

I want to loop through the whole XML to get the inner text value. I need to get the time stamp for the node <Operation type="INTRODUCTION"> . Whenever i get the <Operation type="INTRODUCTION"> , I will go to get the time stamp under this node: <Column name="TimeStamp">2014-05-20T17:43:11.8872105</Column> which is 2014-05-20T17:43:11.8872105 .

I have a code to get the value, but I don't know how to loop through the whole text to get all of them. I am only able to get one.

My code so far:

XmlDocument readDoc = new XmlDocument();
            readDoc.Load(fileName);
            int count = readDoc.SelectNodes("/Runs/Run/Operations/Operation[@type='INTRODUCTION']").Count;
            MessageBox.Show(count.ToString());

                        var node = readDoc.SelectSingleNode("/Runs/Run/Operations/Operation[@type='INTRODUCTION']/Column[@name='TimeStamp']");
MessageBox.Show(node.InnerText);

You can get inner Text for all operation nodes using SelectNodes and then iterating over it to get inner text.

var nodes = readDoc.SelectNodes("/Runs/Run/Operations/Operation/
                                    Column[@name='TimeStamp']");
var innerTexts = nodes.OfType<XmlNode>().Select(n => n.InnerText);

Make sure you add System.Linq namespace to use enumerable extension methods.

Use XmlDocument.SelectNodes instead of XmlDocument.SelectSingleNode to get all matching nodes. You don't need the count of the nodes, but a list of them. After you get the nodes, iterate over them using a regular foreach loop construct:

    var xmlFile = "c:\\input.xml";
    XmlDocument readDoc = new XmlDocument();
    readDoc.Load(xmlFile);
    var nodes = readDoc.SelectNodes("/Runs/Run/Operations/Operation[@type='INTRODUCTION']/Column[@name='TimeStamp']");
    foreach (XmlElement node in nodes)
    {
        Console.WriteLine(node.InnerText);
    }

The output is:

2014-05-20T17:43:11.8872105
2014-05-20T17:58:47.0830259

Another possibility would be to use LINQ2XML in order to get the desired nodes:

try
{           
    var xmlFile = "c:\\input.xml";
    // load the xml file
    var xml = XDocument.Load(xmlFile);
    // find all operations nodes
    var operations = xml.Root.Descendants("Operations").ToList();
    // iterate over all nodes
    foreach (var operation in operations)
    {
        // find the operation node with type INTRODUCTION
        var op = operation.Elements().Where (o => o.Name == "Operation" && (o.Attribute("type").Value.ToUpper() == "INTRODUCTION")).FirstOrDefault();
        if (op != null)
        {
            // find the timestamp node
            var timestamp = op.Elements().Where (o => o.Name == "Column" && (o.Attribute("name").Value.ToUpper() == "TIMESTAMP")).FirstOrDefault();
            if (timestamp != null)
            {
                // and get the value
                Console.WriteLine(timestamp.Value);
            }
        }
    }
}
catch (Exception exception)
{
    Console.WriteLine(exception.Message);
}

The output is the same as above:

2014-05-20T17:43:11.8872105
2014-05-20T17:58:47.0830259

Using LINQ to XML

( using System.Xml.Linq; )

var query = XDocument.Load(xmlPath)
    .Descendants("Operation")
    .Where(w => (string)w.Attribute("type") == "INTRODUCTION")
    .SelectMany(s => s.Elements("Column")
        .Where(w => (string)w.Attribute("name") == "TimeStamp")
        .Select(x => (string)x));

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