zoukankan      html  css  js  c++  java
  • XML 解析中 SelectSingleNode 与 SelectNodes 使用通配符介绍

    俺是 XML XPath的新手,最近因为项目需要,研究了一下基本的两个函数 SelectSingleNode和SelectNodes 是如何实用通配符的,分享以下基本经验:

    假设有段XML 如下所示:

    <PageConfigs>
        <Page Name="Page1" PageMode="0">
            <Position>
                <Left>190</Left>
                <Top>0</Top>
                <Width>1920</Width>
                <Height>1080</Height>
                <ZIndex>1</ZIndex>
            </Position>        
        </Page>
        <Page Name="Page2" PageMode="0" Visible="0">
            <Position>
                <Left>180</Left>
                <Top>0</Top>
                <Width>1920</Width>
                <Height>1080</Height>
            </Position>
            <BizControl DllName="DEF" ClassName="ttt.zzz"/>
            <Animation>
                <StopAnimation>FadeOut</StopAnimation>
                <StartAnimation>FadeIn</StartAnimation>
            </Animation>
        </Page>
    </PageConfigs>

    如果我想要上述说有的参数 Left值,可以实用 SelectNodes:

    $colNodes = $objXML.documentElement.SelectNodes("//Left")
    For $colnode In $colNodes
      ConsoleWrite("From SelectNodes: " & $colNode.text & @CRLF)
    Next
    

    如果我想要 Page2 的参数Left值,可以使用 SelectSingleNode 以及 // 通配符

    $colNode2 = $objXML.documentElement.SelectSingleNode("//Page[@Name='Page2']//Left")
    ConsoleWrite("From SelectSingleNode: " & $colNode2.Text & @CRLF)
    

    当然,有更多的选择:

    $colNode2 = $objXML.documentElement.SelectSingleNode("//*[@Name='Page2']//Left")
    $colNode2 = $objXML.documentElement.SelectSingleNode("*[@Name='Page2']//Left")
    
    $colNode2 = $objXML.documentElement.SelectSingleNode("*[@Name='Page2']/*/Left")
    

    * 前面如果有 /, 那 * 只能配一个节点; 如果*前没有 /,则可以配很多节点;

    以上的通配方法,对SelectNodes也是有效的,但是有一个问题是:

    */*/Left 能够把所有的 Left 节点打印出来

    $colNodes = $objXML.documentElement.SelectNodes("*/*/Left")
    

    但是 */Left 却不行

    以下代码是错误的:

    $colNode2 = $objXML.documentElement.SelectSingleNode("*/Left")
    $colNodes = $objXML.documentElement.SelectNodes("*/Left")
    

    目前还不知道为什么会这样。

  • 相关阅读:
    CodeForces 347B Fixed Points (水题)
    CodeForces 347A Difference Row (水题)
    CodeForces 346A Alice and Bob (数学最大公约数)
    CodeForces 474C Captain Marmot (数学,旋转,暴力)
    CodeForces 474B Worms (水题,二分)
    CodeForces 474A Keyboard (水题)
    压力测试学习(一)
    算法学习(一)五个常用算法概念了解
    C#语言规范
    异常System.Threading.Thread.AbortInternal
  • 原文地址:https://www.cnblogs.com/autotest/p/3431173.html
Copyright © 2011-2022 走看看