java - 如何从JDOM获取节点内容

标签 java xml xml-parsing jdom

我正在使用 import org.jdom.* 在 java 中编写应用程序;

我的 XML 是有效的,但有时它包含 HTML 标签。例如,像这样:

  <program-title>Anatomy &amp; Physiology</program-title>
  <overview>
       <content>
              For more info click <a href="page.html">here</a>
              <p>Learn more about the human body.  Choose from a variety of Physiology (A&amp;P) designed for complementary therapies.&amp;#160; Online studies options are available.</p>
       </content>
  </overview>
  <key-information>
     <category>Health &amp; Human Services</category>

所以我的问题是 overview.content 节点中的 < p > 标签。

我希望这段代码能起作用:

        Element overview = sds.getChild("overview");
        Element content = overview.getChild("content");

        System.out.println(content.getText());

但它返回空白。

如何从 overview.content 节点返回所有文本(嵌套标签和所有文本)?

谢谢

最佳答案

content.getText() 提供即时文本,这仅对具有文本内容的叶元素有用。

技巧是使用 org.jdom.output.XMLOutputter (使用文本模式 CompactFormat)

public static void main(String[] args) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    String xmlFileName = "a.xml";
    Document doc = builder.build(xmlFileName);

    Element root = doc.getRootElement();
    Element overview = root.getChild("overview");
    Element content = overview.getChild("content");

    XMLOutputter outp = new XMLOutputter();

    outp.setFormat(Format.getCompactFormat());
    //outp.setFormat(Format.getRawFormat());
    //outp.setFormat(Format.getPrettyFormat());
    //outp.getFormat().setTextMode(Format.TextMode.PRESERVE);

    StringWriter sw = new StringWriter();
    outp.output(content.getContent(), sw);
    StringBuffer sb = sw.getBuffer();
    System.out.println(sb.toString());
}

输出

For more info click<a href="page.html">here</a><p>Learn more about the human body. Choose from a variety of Physiology (A&amp;P) designed for complementary therapies.&amp;#160; Online studies options are available.</p>

探索其他 formatting选项并根据您的需要修改上面的代码。

"Class to encapsulate XMLOutputter format options. Typical users can use the standard format configurations obtained by getRawFormat() (no whitespace changes), getPrettyFormat() (whitespace beautification), and getCompactFormat() (whitespace normalization). "

关于java - 如何从JDOM获取节点内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7910474/

相关文章:

java - 使用流从 Json 创建嵌套映射

Java正则表达式问题

java - 当 FragmentActivity 在 Android 中进入后台时出现 NotSerializableException

xml - 如何防止 xsd 生成的类被命名为 "NewDataSet"?

xml - 确定 XPath 以检索 XML 中的值

java - 为什么 getClass().getName() 对未打开的模块类起作用?

ruby-on-rails - http POST 错误

java - 如何使用 Xpath 在 XML 树的节点后检索节点?

java - JAXB 解码 XML 类转换异常

ios - 在 iOS 上解析 XML