0

I need to create an XML on JAVA but for multi fields on one element:

<cities>
  <city_insert city_id="123" city_name="São Paulo" />
  <city_insert city_id="456" city_name="Rio de Janeiro"/>
</cities>

As you can see on the example above, the element city_insert need to have city_id, and city_name , one element can have multiples fields.

How this can be done on Java? I've searched for DOM and JDOM parsers but still don't know how this works.

Thank you!

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58

2 Answers2

0

Refer to this question for creating an XML using DOM parser.

Create XML file using java

In order to create an attribute (which you mentioned as fields), call setAttribute() method.

nodelist = doc.getElementsByTagName("city_insert");
for (Element element : nodelist) {
   Element parent = element.getParentNode()
   parent.setAttribute("city_id", "123");
   parent.setAttribute("city_name", "São Paulo");
} 
Community
  • 1
  • 1
Vel
  • 767
  • 5
  • 10
  • 24
0

I allways do this things using jaxb

First, generate an xsd from your xml (there are many free online generators on the net)

For your xml, an online generated xsd look as follows:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="cities">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="city_insert" maxOccurs="unbounded" minOccurs="0">
          <xs:complexType>
            <xs:simpleContent>
              <xs:extension base="xs:string">
                <xs:attribute type="xs:short" name="city_id" use="optional"/>
                <xs:attribute type="xs:string" name="city_name" use="optional"/>
              </xs:extension>
            </xs:simpleContent>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Then, using jaxb (many IDE's like Eclipse have an easy way of doing it) generate jaxb classes from an xsd:

enter image description here enter image description here enter image description here enter image description here

Click finish, then this is java console output:

parsing a schema...
compiling a schema...
com\erax\xml\test\xsd\Cities.java
com\erax\xml\test\xsd\ObjectFactory.java

And the generated classes:

enter image description here

Then just use jaxb marshalling to serialize and deserialize

jlumietu
  • 6,234
  • 3
  • 22
  • 31