gpt4 book ai didi

java - XML文本提取

转载 作者:数据小太阳 更新时间:2023-10-29 02:03:11 25 4
gpt4 key购买 nike

场景:

给定以下 XML 文件:

<a:root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">

<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>

aaaaaaaaaaaaaa

</a:root>

如何提取主要元素内的文本 <a:root> :

"\naaaaaaaaaaaaaa\n"

我现在的代码是:

import java.io.File;
import java.util.Stack;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;


public class Proof {
public static void main(String[] args) {
Document doc = null;
DocumentBuilderFactory dbf = null;
DocumentBuilder docBuild = null;
try {

dbf = DocumentBuilderFactory.newInstance();
docBuild = dbf.newDocumentBuilder();
doc = docBuild.parse(new File("test2.xml"));

System.out.println(doc.getFirstChild().getTextContent());
} catch(Exception e) {
e.printStackTrace();
}
}
}

但它返回我想要的文本 ("aaaaaaaaaaaaaa") + 其余元素的内部文本。输出:

    Apples
Bananas




African Coffee Table
80
120


aaaaaaaaaaaaaa

要求使用额外的 XML java 库!

最佳答案

@Kirill Polishchuk 的回答不正确:

建议:

a:root/text()
  1. 是一个相对表达式,如果未将根 (/) 节点作为上下文节点进行评估,则它不会在提供的 XML 文档中选择任何内容.

  2. 甚至 XPath 表达式:/a:root/text() 也是不正确的,因为它选择了三个文本节点——顶部元素——包括两个纯空白文本节点。

这是一个正确的 XPath 解决方案:

/a:root/text()[string-length(normalize-space()) > 0]

当此 Xpath 表达式应用于提供的 XML 文档时(更正为格式正确):

<a:root
xmlns:a="UNDEFINED !!!!"
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furniture">

<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>

aaaaaaaaaaaaaa

</a:root>

它根据需要选择顶部元素的最后一个(且仅非空白)文本节点子节点:

aaaaaaaaaaaaaa

基于 XSLT 的验证:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:a="UNDEFINED !!!!"
>
<xsl:output omit-xml-declaration="yes" indent="yes"/>

<xsl:template match="/">
<xsl:text>"</xsl:text>
<xsl:copy-of select=
"/a:root/text()
[string-length(normalize-space()) > 0]"/>"

</xsl:template>
</xsl:stylesheet>

当对提供的 XML 文档应用此转换(上图)时,将输出所需的正确选择的文本节点:

"

aaaaaaaaaaaaaa

"

关于java - XML文本提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7292857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com