简体   繁体   中英

How to add multiple attribute values to xml file in JAVA using DOM

I have One XML Like

<root>
<name id="1">Abc</name>
<salary>25000</salary>
</root>

I want something like this

<root>
<name id="1,2">Abc</name>
<salary>25000</salary>
</root>

I am able to create the attribute by using DOM parser as:

Document doc = _docBuilder.newDocument();`
Attr attr = doc.createAttribute("id");
attr.setValue("1");
name.setAttributeNode(attr);

How can I get multiple attribute values for the same attribute.

XML does not support attributes with multiple values .

You could certainly do: attr.setValue("1,2");

However that really isn't very XML friendly. Also, you probably shouldn't have more than one value for an id. You may wish to consider something like this:

<thing>
  <name>Abc</name>
  <reference_ids>
    <id>1</id>
    <id>2</id>
  </reference_ids>
</thing>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM