如何 Select all/multiple个满足以下条件的值

XPATH

/X/X1/X2[@code='b']/X3/value

XML:

<X>
    <X1>
        <X2 code="a">
            <X3>
                <value>x3a1</value>
            </X3>
        </X2>
    </X1>
    <X1>
        <X2 code="b">
            <X3>
                <value>x3b11</value>
            </X3>
        </X2>
    </X1>
    <X1>
        <X2 code="b">
            <X3>
                <value>X3b12</value>
            </X3>
        </X2>
    </X1>

</X>

Code:

import org.dom4j.Document;
import org.dom4j.Node;
Document doc = reader.read(new StringReader(xml));
Node valueNode = doc.selectSingleNode(XPATH);

Expected value

x3b11, X3b12

推荐答案

使用Document.selectNodes()代替Document.selectSingleNode()来 Select 多个 node .

也考虑XPath.selectNodes();以下是DOM4J Cookbook中的完整example:

import java.util.Iterator;

import org.dom4j.Documet;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.XPath;

public class DeployFileLoaderSample {

  private org.dom4j.Document doc;
  private org.dom4j.Element root;

  public void browseRootChildren() {

    /* 
      Let's look how many "James" are in our XML Document an iterate them  
      ( Yes, there are three James in this project ;) )
    */
      
    XPath xpathSelector = DocumentHelper.createXPath("/people/person[@name='James']");
    List results = xpathSelector.selectNodes(doc);
    for ( Iterator iter = results.iterator(); iter.hasNext(); ) {
      Element element = (Element) iter.next();
      System.out.println(element.getName());
    }

    // select all children of address element having person element with attribute and value "Toby" as parent
    String address = doc.valueOf( "//person[@name='Toby']/address" );

    // Bob's hobby
    String hobby = doc.valueOf( "//person[@name='Bob']/hobby/@name" );

    // the second person living in UK
    String name = doc.value( "/people[@country='UK']/person[2]" );
    
    // select people elements which have location attriute with the value "London"
    Number count = doc.numberValueOf( "//people[@location='London']" );
  }
}

Java相关问答推荐

如何在Inspaut中获取当前路径的 * 模式 *?

使用包私有构造函数强制子类Java类

';com.itextpdf.ext.html.WebColors已弃用

如何使用Maven和Spring Boot将构建时初始化、跟踪类初始化正确传递到本机编译

如何才能使我的程序不会要求两次输入?

不推荐使用的Environment.getExternalStorageDirectory().getAbsolutePath()返回的值不同于新的getExternalFilesDir(空)?

为什么Java Annotation接口覆盖对象类中的方法

Spark忽略Iceberg Nessie目录

Com.google.firebase.database.DatabaseException:无法将类型为java.lang.Boolean的值转换为字符串.这是关于什么的?

Java-动态绑定-问题-了解

带有Health Check的Spring Boot BuildPack打破了本机映像构建过程

在处理2个映射表时,没有更多的数据可从套接字读取

如何以编程方式保存workBench.xmi?

IntelliJ IDEA中的JavaFX应用程序无法在资源中找到CSS文件

我无法在我的Spring Boot应用程序中导入CSV依赖项

Java System.getProperty在哪里检索user.home?

整数->;双取消框,但双->;int不';t开箱.为什么?

rest api服务 spring 启动中出现IllegalFormatConversionException

Java方法参数:括号中的类型声明?

如何显示新布局