简体   繁体   中英

Get value of xml node in c#

XML

 <table>
<row>
    <field name="ID">22490</field>
    <field name="post_date">2014-03-24 09:55:50</field>
    <field name="post_title">Joe Bloggs</field>
    <field name="post_status">Live</field>
    <field name="post_modified">2017-07-31 15:33:46</field>
</row>
<row>
    <field name="ID">29078</field>
    <field name="post_date">2017-08-01 08:19:57</field>
    <field name="post_title">Mary Poppins</field>
    <field name="post_status">auto-draft</field>
    <field name="post_modified">2017-08-01 08:19:57</field>
</row><table>

Im trying to loop through the xml above, how can I get the value "Joe Bloggs" from the post_title field above?

Here's what I have so far:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:\\myxmlfile.xml");

XmlNodeList nodeList = xmlDoc.GetElementsByTagName("row");

foreach (XmlNode node in nodeList)
{
    string post_title = /// how can i get this
    string post_status = /// how can i get this
}

I can loop through the nodelist however, I cant get the value within each field.

You can check if property name is what you are expected

foreach (XmlNode node in nodeList)
{
    string temp = XmlNode.SelectSingleNode("field[@name='post_title']").InnerText;
}

This will work for sure.

You can use xPath as well.

        XmlNodeList postTitleFields = xmlDoc.SelectNodes("//field[@name='post_title']");
        foreach (XmlNode postTitleField in postTitleFields)
        {
            string post_title = postTitleField.InnerText;
        }

This is how I resolved the issue:

XmlNodeList orgFields = xmlDoc.SelectNodes("//row");



        foreach (XmlNode org in orgFields)
        {
            post_title = org.ChildNodes[2].InnerText;
            post_status = org.ChildNodes[3].InnerText;

        }

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