0

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>

助けていただければ幸いです。

4

2 に答える 2

3

次のコードを使用できます。

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 and d]" は、c 要素と d 要素を子として含むすべての b 要素を返します。つまり、ループ内で手動でチェックする必要はありません。

于 2012-05-25T10:30:07.157 に答える
0

私はこのように解決しました:

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
    }
}

非常にエレガントに見えないため、より良いソリューションを歓迎します。

于 2012-05-25T09:28:45.010 に答える