【发布时间】:2021-07-25 01:11:50
【问题描述】:
我试图在我的 pom.xml 中为我的依赖项标签提取 xml 嵌套内容。 但即使指定了位置,它也没有得到正确的依赖标签。有什么帮助吗? 这是我的 pom.xml
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<build>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<dependencies>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-nodeps</artifactId>
<version>1.8.1</version>
</dependency>
</dependencies>
</build>
<dependencies>
<dependency>
<groupId>com.intent.tm</groupId>
<artifactId>commons-io</artifactId>
<version>1.0.0.1</version>
</dependency>
<!-- For Compress JS -->
<dependency>
<groupId>com.yahoo.platform.yui</groupId>
<artifactId>yuicompressor</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.sybase</groupId>
<artifactId>EccpressoFIPSJca</artifactId>
<version>7.0</version>
</dependency>
这是我的代码
private static String nodeToString(Node node) throws TransformerException {
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.transform(new DOMSource(node), new StreamResult(buf));
return (buf.toString());
}
File fXmlFile = new File(prop.getProperty("testFile"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document;
Node result = null;
document = dbf.newDocumentBuilder().parse(fXmlFile);
XPath xPath = XPathFactory.newInstance().newXPath();
String xpathStr = "//project//dependencies";
result = (Node) xPath.evaluate(xpathStr, document, XPathConstants.NODE);
log.info(nodeToString(result));
实际输出:
<dependencies>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-nodeps</artifactId>
<version>1.8.1</version>
</dependency>
</dependencies>
预期输出:
<dependencies>
<dependency>
<groupId>com.intent.tm</groupId>
<artifactId>commons-io</artifactId>
<version>1.0.0.1</version>
</dependency>
<!-- For Compress JS -->
<dependency>
<groupId>com.yahoo.platform.yui</groupId>
<artifactId>yuicompressor</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>com.sybase</groupId>
<artifactId>EccpressoFIPSJca</artifactId>
<version>7.0</version>
</dependency>
由于某种原因,当指定的位置不是构建时,它会在构建标记中打印依赖项。我很困惑为什么会发生这种情况,并且无论如何都能得到我的预期?
【问题讨论】:
-
xPath.evaluate(xpathStr, document, XPathConstants.NODE);返回一个节点。 evaluate(xpathStr, document, XPathConstants.NODESET) 将返回节点列表。 // 匹配下的任何内容,因此您在项目下的任何地方都要求依赖项,不仅在子项中,而且在孙子项中。
-
@JPMoresmau 那么应该修改什么来实现这一点?你能把整个代码粘贴到答案中吗
-
线程“主”java.lang.ClassCastException 中的异常:com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList 无法转换为 org.w3c.dom.Node 我得到当我更改为 NODESET
-
抱歉,忽略该建议
-
@JP Moresmau 你能看看这个我面临的关于 xpath 的问题stackoverflow.com/questions/67361493/…
标签: java xml xpath xml-parsing