使用 JAXB 提取 XML 元素的内部文本 [英] Using JAXB to extract inner text of XML element

查看:34
本文介绍了使用 JAXB 提取 XML 元素的内部文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下 XML 配置文件:

Given the following XML configuration file:

<main>
  <name>JET</name>
  <maxInstances>5</maxInstances>
  <parameters>
    <a>1</a>
    <b>
      <b1>test1</b1>
      <b2>test2</b2>
    </b>
  </parameters>
</main>

我需要提取 name 和 maxInstances 元素的值,然后提取 parameters 元素的整个内部文本.例如

I need to extract the value of the name and maxInstances elements and then the whole inner text of the parameters element. e.g.

name = "JET"
maxInstances = 5
parameters = "<a>1</a><b><b1>test1</b1><b2>test2</b2></b>"

最终,参数块可以包含任何格式良好的 XML.

Ultimately the parameters block can contain any well formed XML.

以下代码适用于 name 和 maxInstances,但不适用于参数:

The following code works for name and maxInstances but not parameters:

@XmlRootElement(name="main")
public class Main {

    @XmlElement(name="name", required="true")
    private String name;

    @XmlElement(name="maxInstances", required="true")
    private Integer maxInstances;

    @XmlElement(name="parameters")
    private String parameters;

}

我尝试根据以下想法寻找解决方案,但找不到合适的方法.

I've tried looking at solutions based on the following ideas but can't find something appropriate.

是否有不同的类型可以用于表示 XML 树的参数对象,我可以解析它以生成字符串?例如

Is there a different type I can use for the parameters object representing the XML Tree that I could parse to produce a string? e.g.

@XmlElement(name="parameters")
private XmlNodeObject parametersNode;

public String getParameters() {
    // Collapse node to single line of text
    return innerText;
}

或者我需要使用某种不同类型的注释吗?

Or do I need to use some different kind of annotation?

@XmlSpecialAnnotation(...)
@XmlElement(name="parameters")
private String parameters;

我需要切换到不同风格的解析器吗?使用两种风格的解析器是个好主意还是坏主意?

Do I need to switch to a different style of parser? Is it a good/bad idea to use two styles of parser?

推荐答案

最接近的方法是将参数"映射到 DOM 树,方法是将变量声明为 org.w3c.dom.Node.(实际上,声明了一个 JAXBElement).

The closest you could come is to map 'parameters' to a DOM tree, by declaring the variable to be org.w3c.dom.Node. (Actually, declaring a JAXBElement).

详情参见http://jaxb.java.net/guide/Avoid_strong_databinding.html.这为您提供了模式优先的处方,您可以通过 xsd2java 运行该模式并查看输出来了解如何从 java 开始.

For details, see http://jaxb.java.net/guide/Avoid_strong_databinding.html. That gives you the schema-first prescription, you can see how to start from java by running that schema through xsd2java and looking at the output.

要获取字符串,您必须从 DOM 中进行序列化.

To get a string you'll have to serialize from the DOM.

或者,更具体地说:

这里描述的是 xsd:任何处理,因此

  @XmlAnyElement
  public List<Element> getParameters();

其中 Element 是 DOM 接口.

Where Element is the DOM interface.

这篇关于使用 JAXB 提取 XML 元素的内部文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆