【问题标题】:Parse XML into HTML using Java org.w3c.dom使用 Java org.w3c.dom 将 XML 解析为 HTML
【发布时间】:2012-04-12 19:49:06
【问题描述】:

通过 API,我得到了一个 XML 文件,我试图通过 org.w3c.dom 和 XPath 对其进行解析。 XML 文件的一部分描述了 HTML 内容:

<Para>Since 2001, state and local health departments in the US have accelerated efforts to prepare for bioterrorism and other high-impact public health emergencies. These activities have been spurred by federal funding and guidance from the US Centers for Disease Control and Prevention (CDC) and the Health Resources and Services Administration (HRSA) 
     <CitationRef CitationID="B1">1</CitationRef>  
     <CitationRef CitationID="B2">2</CitationRef> . Over time, the emphasis of this guidance has expanded from bioterrorism to include "terrorism and non-terrorism events, including infectious disease, environmental and occupational related emergencies" 
     <CitationRef CitationID="B4">4</CitationRef> as well as pandemic influenza.
</Para>

这应该变成这样:

<p>Since 2001, state and local health departments in the US have accelerated efforts to prepare for bioterrorism and other high-impact public health emergencies. These activities have been spurred by federal funding and guidance from the US Centers for Disease Control and Prevention (CDC) and the Health Resources and Services Administration (HRSA) 
     <a href="link/B1">1</a>  
     <a href="link/B2">3</a> . Over time, the emphasis of this guidance has expanded from bioterrorism to include "terrorism and non-terrorism events, including infectious disease, environmental and occupational related emergencies" 
     <a href="link/B4">4</a> as well as pandemic influenza.
</p>

关于如何完成此任务的任何建议?主要问题是检索标签并替换它们,同时保持它们的位置。

【问题讨论】:

  • 这听起来像是 XSLT 的完美工作,因为它是一种将 XML 输入转换为其他 XML 格式或 HTML 的语言。如果您需要有关 XSLT 代码的帮助,请将 XSLT 标记添加到您的问题中。

标签: html xml parsing xpath


【解决方案1】:

以下是使用 XSLT 的方法:

<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="1.0">

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="Para">
  <p>
    <xsl:apply-templates select="@* | node()"/>
  </p>
</xsl:template>

<xsl:template match="CitationRef[@CitationID]">
  <a href="link/{@CitationID}">
    <xsl:apply-templates/>
  </a>
</xsl:template>

</xsl:stylesheet>

【讨论】:

  • 感谢您的回复,我正在研究 XSLT (rgagnon.com/javadetails/java-0407.html),有没有办法让我获得您提供的 XSL 文件、需要解析的 XML 和所有输出是一个字符串(所以不是文件)?
  • 我很确定使用 JAXP 可以将输入、样式表和结果作为字符串,这只是使用正确的源 docs.oracle.com/javase/6/docs/api/javax/xml/transform/stream/… 和结果类型(例如 StreamSource over StringReader)的问题。我会把它留给比我更熟悉 Java API 的人。
  • 感谢您的提示,我成功了!对于输入 XML,我使用了以下代码:nl = (Node) xpath.evaluate("//expression/here",doc, XPathConstants.NODE); DOMSource source = new DOMSource(nl);
猜你喜欢
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多