SimpleXML:同一节点上的值和属性

SimpleXML: Value and Attribute on same Node

是否可以使用简单XML 来处理节点属性和值? 例如在标签“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>

我找不到在我的代码中处理节点内容的方法。 我对此 XML 的示例代码是:

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;

}

现在我正在寻找 Sender.content 的注释,它解决了值 note/from/Jani

根据官方文档,可以使用注解@Text:

示例如下:

向元素添加文本和属性

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.


您的代码将如下所示:

public class Sender 
{

    @Text
    private String content;

    @Attribute(name = "name")
    private String attribute;

}

http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php