3

How can I get an element in Xpath using complex condition?

For example:

<?xml version="1.0" encoding="UTF-8"?>
<stock xmlns="http://localhost/aaabbb">
<item item-id="1">
 <name xml:format="short">This is a short name</name>
 <name xml:format="long">This is a LONG name</name>
</item>
</stock>

Target: to get the text of the tag WHERE xml:format="long".

Thanks in advance for your help!

4

3 に答える 3

6

Take a look at this: http://www.w3schools.com/xpath/xpath_syntax.asp. The example you are requesting:

The XML document:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore> 

The XPATH:

//title[@lang='eng']    Selects all the title elements that have an attribute named lang with a value of 'eng'

So you should do this:

//name[@xml:format='long']
于 2012-06-10T08:03:35.460 に答える
1

特定のケースでは、XML ドキュメントはデフォルトの名前空間にないため、次のような XPath 式になります。

/stock/item/name

どのノードも選択しません

使用:

/*/*/*[name()='name' and @xml:format = 'long']/text()

または使用

string(/*/*/*[name()='name' and @xml:format = 'long'])

name最初の式は、名前が(名前空間に関係なく) であり、XML ドキュメントの最上位要素の孫であるすべての要素のすべてのテキスト子ノードを選択します。

2 番目の式は、XML ドキュメントの最初の要素の文字列値を生成します。その名前はname(名前空間に関係なく)、XML ドキュメントの最上位の要素の孫です。

XSLT ベースの検証:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/">
     <xsl:copy-of select="/*/*/*[name()='name' and @xml:format = 'long']/text()"/>
===========
     <xsl:copy-of select="string(/*/*/*[name()='name' and @xml:format = 'long'])"/>
 </xsl:template>
</xsl:stylesheet>

この変換が提供された XML ドキュメントに適用されると、次のようになります。

<stock xmlns="http://localhost/aaabbb">
    <item item-id="1">
        <name xml:format="short">This is a short name</name>
        <name xml:format="long">This is a LONG name</name>
    </item>
</stock>

2 つの Xpath 式が評価され、選択された要素 (最初のもの) と生成された文字列の結果 (2 番目のもの) が出力にコピーされます

This is a LONG name
===========
This is a LONG name
于 2012-06-10T14:24:58.257 に答える
0

以下のXMLファイルを持っている

<?xml version="1.0" encoding="UTF-8"?>
<stock xmlns="http://localhost/aaabbb">
<item item-id="1">
 <name xml:format="short">This is a short name</name>
 <name xml:format="long">This is a LONG name</name>
</item>
</stock>

最初xPathにノード リストの を指定します。

XmlNodeList nodeList = root.SelectNodes("/stock/item");

次に、必要なリストの名前ノードを指定します: ('Long' 属性値を持つノード)

XmlNode name = nodeList.Item(0).SelectSingleNode(string.Format("/stock/item/name[@xml:format="Long"]"));

3 番目に、このノード内のテキストを取得します。

string result = name.InnerText;
于 2012-08-16T11:24:12.393 に答える