【问题标题】:Java convert a DOM object into paragraphsJava 将 DOM 对象转换为段落
【发布时间】:2015-07-06 14:21:22
【问题描述】:

是否有类似于 java 中的 python 函数lmxl.sax.saxify [1] 的函数来从 DOM 生成 SAX 事件并针对 SAX ContentHandler 触发它们。 主要目的是将 DOM 对象转换为段落列表。 给定这个 html sn-p

<p> Here is a text! 
<ul><li>list1</li><li>list2</li></ul>
</p>

我想要的输出是:

  • 第 1 段:这是一段文字!
  • 第二段:list1
  • 第三段:list2

[1]http://lxml.de/api/lxml.sax-module.html#saxify

【问题讨论】:

  • 所以您想从 DOM 文档中检索所有文本节点?

标签: java xml dom sax


【解决方案1】:

是的,您可以使用 DOMSource 和 SAXResult 运行转换,请参阅http://www.java2s.com/Code/Java/XML/GeneratingSAXParsingEventsbyTraversingaDOMDocument.htm

Source source = new DOMSource(doc);

URI uri = new File("infilename.xml").toURI();
source.setSystemId(uri.toString());

DefaultHandler handler = new MyHandler();
SAXResult result = new SAXResult(handler);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);

但是你为什么不从你的 DOM 中提取你想要的信息呢?

【讨论】:

  • 那是怎么回事?我是 DOM 解析新手
  • 另外,我要解析的文件是 html 而不是 xml。
【解决方案2】:

如果您想从 DOM 文档中检索所有文本节点(这是一个与原始问题不同的问题),那么 Xpath 是从 DOM 文档中搜索和提取数据的最简单(也是最有效)的方法

这是你需要的一段代码:

Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("/path/example.html");
XPath xPath =  XPathFactory.newInstance().newXPath();
String pattern = "//*/text()"; // retrieve all text nodes in the doc
NodeList nl = (NodeList)xPath.compile(pattern)
        .evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nl.getLength() ; i++) {
    Node n = nl.item(i);
    String text = n.getNodeValue().trim();
    // skip over whitespace-only text
    if (text != null && text.isEmpty() == false) {
        System.out.println(text);
    }
}

【讨论】:

  • 感谢您的回复。我试过你的代码,但我遇到了这个错误[Fatal Error] loose.dtd:31:3: The declaration for the entity "HTML.Version" must end with '&gt;'你知道是不是因为我解析的是html而不是xml吗?
  • 快速谷歌搜索表明这确实是 SGML DTD 的情况。这里有一个帖子提出了克服这个问题的方法stackoverflow.com/questions/155101/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
  • 2013-03-03
  • 1970-01-01
  • 2019-02-24
  • 2017-04-29
  • 1970-01-01
  • 2012-08-01
相关资源
最近更新 更多