Java如何在JDOM中获取XML元素的文本内容?
package org.nhooo.example.jdom;import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import java.io.IOException;
import java.io.StringReader;
public class JDOMElementTextContent {
public static void main(String[] args) {
String xml = "<root>" +
" <paragraph>" +
" Lorem ipsum dolor sit amet, consectetur adipisicing " +
" elit, sed do eiusmod tempor incididunt ut labore et " +
" dolore magna aliqua. Ut enim ad minim veniam, quis " +
" nostrud exercitation ullamco laboris nisi ut aliquip " +
" ex ea commodo consequat. Duis aute irure dolor in " +
" reprehenderit in voluptate velit esse cillum dolore " +
" eu fugiat nulla pariatur. Excepteur sint occaecat " +
" cupidatat non proident, sunt in culpa qui officia " +
" deserunt mollit anim id est laborum." +
" </paragraph>" +
"</root>";
SAXBuilder builder = new SAXBuilder();
try {
Document document = builder.build(new StringReader(xml));
Element root = document.getRootElement();
Element paragraph = root.getChild("paragraph");
//返回直接保存在该元素下的文本内容
//字符串。这包括了这个元素中的所有文本,
//包含空格和CDATA节(如果它们存在的话)。
String content = paragraph.getText();
System.out.println("content = " + content);
//返回此元素的文本内容及其周围的
//删除了空格。如果元素不存在文本值,
//或者,如果只存在空白,则返回空字符串。
String contentTrimmed = paragraph.getTextTrim();
System.out.println("contentTrimmed = " + contentTrimmed);
//返回此元素的文本内容及其周围的
//删除空白,将内部空白规范化为单个
// 空间。如果元素不存在文本值,或者
//如果存在空白,则返回空字符串。
String contentNormalize = paragraph.getTextNormalize();
System.out.println("contentNormalize = " + contentNormalize);
} catch (JDOMException | IOException e) {
e.printStackTrace();
}
}
}
Maven 依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar --><dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
以上是 Java如何在JDOM中获取XML元素的文本内容? 的全部内容, 来源链接: utcz.com/z/326328.html