条件に基づいてxmlファイルからテキストブロックを抽出する

条件に基づいてxmlファイルからテキストブロックを抽出する

fqdns次のファイルからコンテンツを抽出したいが、device場所によってのみ可能です。statusnew

<device id='10.72.48.215'>
    <address>10.72.48.215</address>
    <status>old</status>
    <fqdns>10.72.48.215</fqdns>
    <parent></parent>
    <type>Unknown</type>
    <ports>
    </ports>
    <operatingsystems>
    </operatingsystems>
</device>
<device id='10.72.48.216'>
    <address>10.72.48.216</address>
    <status>new</status>
    <fqdns>10.72.48.216</fqdns>
    <parent></parent>
    <type>Unknown</type>
    <ports>
    </ports>
    <operatingsystems>
    </operatingsystems>
</device>

10.72.48.216だから上記の場合(代わりに)を取得したいと思います10.72.48.215

ベストアンサー1

XML宣言を追加し、device最上位要素に両方の要素を含める場合は、XPathを使用してファイルを処理できます。

$ cat ./248127.xml
    <device id='10.72.48.215'>
            <address>10.72.48.215</address>
            <status>old</status>
            <fqdns>10.72.48.215</fqdns>
            <parent></parent>
            <type>Unknown</type>
            <ports>
            </ports>
            <operatingsystems>
            </operatingsystems>
    </device>
    <device id='10.72.48.216'>
            <address>10.72.48.216</address>
            <status>new</status>
            <fqdns>10.72.48.216</fqdns>
            <parent></parent>
            <type>Unknown</type>
            <ports>
            </ports>
            <operatingsystems>
            </operatingsystems>
    </device>

$ ( echo '<?xml version="1.0"?><doc>'; cat ./248127.xml ; echo '</doc>' ) \
    | xpath -q -e '//device[status/text()="new"]/fqdns'
<fqdns>10.72.48.216</fqdns>

おすすめ記事