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.

1
  • What object model are you mapping the XML to? Commented Feb 19, 2013 at 12:03

1 Answer 1

2

You could do the following

JAVA MODEL

JAXB (JSR-222) implementations require that you have an object model to convert your XML documents to.

A

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;
    }

}

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;
    }

}

DEMO CODE

Once you have your XML converted to Java objects, you can navigate your objects to get the desired data.

Demo

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());
    }

}

Output

www
abcde
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.