Is it possible, to address a nodes Attributes and Value with SimpleXML?
For example in tag "from":
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from name="test">Jani</from>
<heading>Reminder</heading>
<body>Dont forget me this weekend!</body>
</note>
I couldn’t find a way to address the content of the node in my code.
My example code for this XML would be:
public class Note
{
@Element(name = "to")
private String to;
@Element(name = "from")
private Sender from;
@Element(name = "heading")
private String heading;
@Element(name = "body")
private String body;
}
public class Sender
{
private String content;
@Attribute(name = "name")
private String attribute;
}
Now im looking for a annotation for Sender.content which addresses the value note/from/Jani
>Solution :
According to the official documentation, you can use the annotation @Text:
Example below:
Adding text and attributes to elements
As can be seen from the previous example annotating a primitive such
as a String with the Element annotation will result in text been added
to a names XML element. However it is also possible to add text to an
element that contains attributes. An example of such a class schema is
shown below.
@Root
public class Entry {
@Attribute
private String name;
@Attribute
private int version;
@Text
private String value;
public int getVersion() {
return version;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
}
Here the class is annotated in such a way that an element contains two
attributes named version and name. It also contains a text annotation
which specifies text to add to the generated element. Below is an
example XML document that can be generated using the specified class
schema.
<entry version='1' name='name'>
Some example text within an element
</entry>
The rules that govern the use of the Text annotation are that there
can only be one per schema class. Also, this annotation cannot be used
with the Element annotation. Only the Attribute annotation can be used
with it as this annotation does not add any content within the owning
element.
Your code will then look like:
public class Sender
{
@Text
private String content;
@Attribute(name = "name")
private String attribute;
}
http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php