2

My XML Structure.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<A>
    <B ID="www">
        <C>abcde</C>
    </B>
</A>

I use Unmarshaller.

System.out.println(c.toString());   => abcde

I want attribute information.

System.out.println(????????);        => ID or count

help me please.

4

1 回答 1

2

您可以执行以下操作

JAVA模型

JAXB (JSR-222) 实现要求您有一个对象模型来将您的 XML 文档转换为。

一个

import javax.xml.bind.annotation.*;

@XmlRootElement(name="A")
public class A {

    private B b;

    @XmlElement(name="B")
    public B getB() {
        return b;
    }

    public void setB(B b) {
        this.b = b;
    }

}

import javax.xml.bind.annotation.*;

public class B {

    private String id;
    private String c;

    @XmlAttribute(name = "ID")
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @XmlElement(name = "C")
    public String getC() {
        return c;
    }

    public void setC(String c) {
        this.c = c;
    }

}

演示代码

将 XML 转换为 Java 对象后,您可以导航对象以获取所需的数据。

演示

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(A.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum14951650/input.xml");
        A a = (A) unmarshaller.unmarshal(xml);

        System.out.println(a.getB().getId());
        System.out.println(a.getB().getC());
    }

}

输出

www
abcde
于 2013-02-19T15:13:29.820 回答