【问题标题】:How to parse XML with namespace using JAXB如何使用 JAXB 解析带有命名空间的 XML
【发布时间】:2023-04-03 09:15:01
【问题描述】:

我刚开始学习 XML 和 JAXB,做了一些如何编组和解组数据的示例。但是,我仍然无法使用命名空间解析 XML。谁能帮我这个例子

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:Uuid xmlns:ns2="com/mypackage/test">
    <value>123456789</value>
</ns2:Uuid>

这是我创建的类

@XmlRootElement (name = "Uuid", namespace = "com/mypackage/test")
public class Uuid {


protected String value;

@XmlElement(namespace = "ns2")
public String getValue() {
    return this.value;
}

public void setValue(String value) {
    this.value = value;
  }
}

获取空输出

Uuid uuid = null;
    JAXBContext jbContext;
    try {
        jbContext = JAXBContext.newInstance(Uuid.class);
        Unmarshaller jbUnmarshaller = jbContext.createUnmarshaller();
        uuid = (Uuid) jbUnmarshaller.unmarshal(file);

        System.out.println(uuid.getValue());
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

谢谢

【问题讨论】:

    标签: xml namespaces jaxb


    【解决方案1】:

    您在 Uuid 对象的 value 字段上声明了一个命名空间,而您的 xml 值元素没有命名空间。

    要么删除 @XmlElement 注释中的命名空间,要么在你的 Uuid 根元素中使用 xmlns 属性向你的 xml 添加一个默认命名空间,或者将命名空间显式添加到你的元素中 (&lt;ns2:value&gt;94305&lt;/ns2:value&gt;)

    这些选项中的任何一个都可以解决您的问题。

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      相关资源
      最近更新 更多