[英]Get value of xml node in c#
XML 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? 我试图遍历上面的xml,如何从上面的post_title字段中获取“ Joe Bloggs”值?
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. 您也可以使用xPath。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.