![](/img/trans.png)
[英]How to read/write nodes and child nodes from xml file in c# maybe using xpath?
[英]How do I extract child nodes from XML file using XPath when both child nodes must exist?
我正在嘗試從xml文檔中提取某些值。 在下面的示例中,我想將存儲在“ c”和“ d”節點中的值存儲在列表中,但僅在“ b”節點同時包含“ c”和“ d”的情況下。 到目前為止,我擁有的代碼循環遍歷所有“ b”節點,但是我不確定在while循環中放入什么,或者這是否是最佳方法。
XmlDocument attrsXML = new XmlDocument();
attrsXML.LoadXml(dbReader["SampleXml"].ToString());
XPathNavigator nav = attrsXML.CreateNavigator();
XPathNodeIterator attribNodes = nav.Select("/a/b");
while (attribNodes.MoveNext())
{
// What do I need to put here in order to extract the 'c' and 'd' nodes?
// Any other nodes can be ignored (such as 'e' above). I am only interested
// when 'b' contains both 'c' AND 'd'.
}
從數據庫加載的“ SampleXml”在哪里:
<a>
<b>
<c>Extract this</c>
<d>And this</d>
<e>not this</e>
</b>
<b>
<c>not this</c>
<e>not this</e>
</b>
<b>
<c>Extract this</c>
<d>And this</d>
</b>
</a>
任何幫助表示贊賞。
您可以使用以下代碼:
XmlDocument attrsXML = new XmlDocument();
attrsXML.LoadXml(dbReader["SampleXml"].ToString());
XmlNodeList nodeList = attrsXML.SelectNodes("/a/b[c and d]");
foreach (XmlNode xmlNode in nodeList)
{
string cText = xmlNode.SelectSingleNode("c").InnerText;
string dText = xmlNode.SelectSingleNode("d").InnerText;
}
XPath“ / a / b [c和d]”返回所有包含c和d元素的b個元素作為子元素,這意味着您不需要在循環內手動檢查它。
我是這樣解決的:
while (attribNodes.MoveNext())
{
string cText = String.Empty;
string dText = String.Empty;
XPathNavigator nav2 = attribNodes.Current;
var cNode = nav2.SelectSingleNode("c");
if (cNode != null)
{
cText = nameNode.ToString();
var dNode = nav2.SelectSingleNode("d");
if (dNode != null)
{
dText = dNode.ToString();
}
}
if (dText != String.Empty && cText != String.Empty)
{
// Problem solved
}
}
歡迎任何更好的解決方案,因為它看起來不太優雅。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.