JAXBを使用してさまざまなXMLのさまざまなフィールドを動的に抽出しようとしています。たとえば、次のような例があります。JAXBを使用してXMLを動的に読み取る
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Entities TotalResults="1">
<Entity Type="test-set-folder">
<Fields>
<Field Name="id">
<Value>1760</Value>
</Field>
<Field Name="ver-stamp">
<Value>0</Value>
</Field>
<Field Name="parent-id">
<Value>109</Value>
</Field>
<Field Name="last-modified">
<Value>2017-02-24 15:50:36</Value>
</Field>
<Field Name="hierarchical-path">
<Value>AAAAAAABN</Value>
</Field>
<Field Name="description">
<Value />
</Field>
<Field Name="view-order" />
<Field Name="name">
<Value>ABCDEF</Value>
</Field>
<Field Name="attachment">
<Value />
</Field>
<Field Name="workflow">
<Value />
</Field>
</Fields>
<RelatedEntities />
</Entity>
</Entities>
これは、すべてのXMLのフィールドが動的に変更されるため、この処理を動的に実行したいと考えています。私の基本的な目的は、各フィールドを私の便宜のために使用するようにキャプチャすることです。
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRootElement(name = "Entities")
@XmlAccessorType(XmlAccessType.FIELD)
public class Entity {
@XmlAttribute
int id;
@XmlAnyAttribute
Map<QName, String> otherAttributes;
String name;
@XmlAnyElement(lax=true)
List<Object> otherElements;
}
次のようにEntity.javaを呼び出すためのコードは次のとおりです:
import java.io.File;
import java.util.Map.Entry;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Entity.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("path\\to xml\\file");
Entity entity = (Entity) unmarshaller.unmarshal(xml);
// Mapped XML Attribute
System.out.println("entity.id");
System.out.println(" " + entity.id);
// Other XML Attributes
System.out.println("entity.otherAttributes");
for(Entry<QName, String> entry : entity.otherAttributes.entrySet()) {
System.out.println(" " + entry);
}
// Mapped XML Element
System.out.println("entity.name");
System.out.println(" " + entity.name);
// Other XML Elements
System.out.println(entity.otherElements);
for(Object object : entity.otherElements) {
System.out.println(" " + object);
}
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(entity, System.out);
}
}
私の混乱は、ということです例えば、field.id
は1760年、など
次のように私のEntity.java
があるを返す必要がありますXMLは入れ子になっています。すなわち、第4層のデータが私が興味を持っているものです:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<Entities TotalResults="1">
<Entity Type="test-set-folder">
<Fields>
<Field Name="id">
<Value>1760</Value>
</Field>
.
.
.
Entityクラスのコードが間違っている可能性がありますが、誰かがそれについてどうやって手伝ってくれますか?
これをコメントとして追加するとより適切になります –
この回答がどのように役立つのか説明できますか? lakh xmlsを取得するためにxsdsをどのように生成する必要がありますか? –