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

查看:148
本文介绍了使用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元素的值,然后提取参数的整个内部文本元件。例如

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?

推荐答案

你最接近的是映射'参数'通过将变量声明为 org.w3c.dom.Node ,到DOM树。 (实际上,声明一个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();

其中元素是DOM接口。

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

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