プロが教える店舗&オフィスのセキュリティ対策術

xml文書1

<?xml version="1.0">
<customer0>
<name>aaaa</name>
<tel>1234</tel>
</customer0>
<customer1>
<name>bbbb</name>
<tel>2345</tel>
</customer1>

xml文書2

<?xml version="1.0">
<customer>
<name>aaaa</name>
<tel>1234</tel>
</customer>
<customer>
<name>bbbb</name>
<tel>2345</tel>
</customer>

xml文書1のcustomerの子要素(name,tel)を全て取得したいです。
ルートノードから辿って行くのではなく、ダイレクトにアクセスしたいです。
xPath式で子要素を全て取り出すことはできますでしょうか?

xml文書2であれば「//customer」で可能だと思うんですが。

宜しくお願い致します。

A 回答 (2件)

ルートノードがない地点でXML文書として認められない。


何かの書き間違いであると信じて要望を予測してみる。少なくとも何かのヒントにはなるはず
==============Q4374721-1.xml================
<?xml version="1.0" encoding="UTF-8"?>
<customers>
<customer0>
<name>aaaa</name>
<tel>1234</tel>
</customer0>
<customer1>
<name>bbbb</name>
<tel>2345</tel>
</customer1>
</customers>
==============Q4374721-1.xsl================
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" /> <!-- お好みで -->

<!--
templateは後から書いたものが優先されるので,
ルート要素のcustomers要素は下のテンプレートに引っかかる

数字をチェックしているわけではなく単にcustomerで始まる要素をマッチさせているだけなので
customersABCのような要素でもヒットする。
まぁその辺はXPathのsubstring関数とか,number関数に通してNaNかチェックしたり
andで条件つなげればどうにでもなるでしょ?
-->

<xsl:template match="//*[starts-with(local-name(),'customer') and namespace-uri()='']">
<item>
<xsl:value-of select="name" />
</item>
</xsl:template>

<xsl:template match="/*">
<list>
<xsl:apply-templates />
</list>
</xsl:template>


</xsl:stylesheet>
==============Q4374721-2.xml(結果)================
<?xml version="1.0" encoding="UTF-16"?>
<list>
<item>aaaa</item>
<item>bbbb</item>
</list>
    • good
    • 0
この回答へのお礼

ありがとうございます。
関数が使えるんですね。参考になりました。

お礼日時:2008/10/03 16:30

できる事はできるけど文書1のxmlは美しくないねぇ・・・



結局xPathで使われるのはmatchする文字列を生成できれば良いので名前+数値と判っているならそういう文字列合成をしてアクセスすれば良い。

できたかどうか判らないけど customer* とか。
    • good
    • 0
この回答へのお礼

ありがとうございます。

お礼日時:2008/10/03 16:29

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!