为多个节点选择xml路径

时间:2015-05-30 10:53:41

标签: xml xpath

我的XML结构如下:

<Children>
  <Stand>
    <Basics>
      <Attribute Name="Name">User1</Attribute>
      <Attribute Name="Scope">LOCAL</Attribute>
    </Basics>
    <Attributes/>
    <Relationship>
      <Attribute Name="Quantity">2</Attribute>
      <Attribute Name="good Quantity">0</Attribute>
    </Relationship>
  </Stand>
  <Stand>
    <Basics>
      <Attribute Name="Name">User2</Attribute>
      <Attribute Name="Scope">LOCAL</Attribute>
    </Basics>
    <Attributes/>
    <Relationship>
      <Attribute Name="Quantity">5</Attribute>
      <Attribute Name="good Quantity">0</Attribute>
    </Relationship>
  </Stand>
</Children>

我想从上面的XML中提取NameScopeQuantitygood Quantity。我正在使用Xpath表达式:

//Children/Stand/* [self::Basics | self::Relationship]

我得到的结果是:

User1   LOCAL   null   null
null    null    2      0
User2   LOCAL   null   null
null    null    5      0

我希望结果如下:

User1   LOCAL   2      0
User2   LOCAL   5      0

任何人都可以帮助获得所需的输出吗?

2 个答案:

答案 0 :(得分:1)

我相信这个问题除了xpath之外还有别的东西,因为xpath只能返回节点或像字符串一样的原始类型,类似于那样,而不是表结构化的结果。

在仅xpath的观点上,您当前的xpath选择<Basics><Relationship>元素,每个元素都在结果表的单独行中。我相信您希望xpath选择<Stand>元素:

//Children/Stand

然后相对于当前<Stand>元素进行列选择:

Basics/Attribute[@Name="Name"]
Basics/Attribute[@Name="Scope"]
Relationship/Attribute[@Name="Quantity"]
Relationship/Attribute[@Name="good Quantity"]

这样,对应于同一<Attribute>祖先的所有<Stand>元素都显示在结果表的同一行中。

答案 1 :(得分:1)

您是否考虑过应用脚本语言?因为我所做的就是这样,在var visibleRect = CGRectMake (newImageVC.scrollView.contentOffset.x * scale, newImageVC.scrollView.contentOffset.y * scale, newImageVC.scrollView.bounds.size.width * scale, newImageVC.scrollView.bounds.size.height * scale) 中使用相当优秀的perl库进行XML解析。

XML::Twig

或者,如果您更喜欢更简洁(并假设属性以相同的方式排序):

#!/usr/bin/perl
use strict;
use warnings;

use XML::Twig;

sub print_user {
    my ( $twig, $stand ) = @_;

    print join( "\t",
        $stand->get_xpath( './Basics/Attribute[@Name="Name"]',     0 )->text,
        $stand->get_xpath( './Basics/Attribute[@Name="Scope"]',    0 )->text,
        $stand->get_xpath( './Relationship/Attribute[@Name="Quantity"]', 0 )->text,
        $stand->get_xpath( './Relationship/Attribute[@Name="good Quantity"]', 0 )
            ->text,
        ),
        "\n";
}

XML::Twig->new( 'twig_handlers' => { 'Stand' => \&print_user } ) -> parsefile ('xmlfile');
相关问题