简体   繁体   English

如何使用DOM将多个属性值添加到JAVA中的xml文件中

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

I have One XML Like 我有一个像XML

<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: 我可以通过使用DOM解析器来创建属性:

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 . XML 不支持具有多个值的属性

You could certainly do: attr.setValue("1,2"); 您当然可以这样做: attr.setValue("1,2");

However that really isn't very XML friendly. 但是,这确实不是非常友好的XML。 Also, you probably shouldn't have more than one value for an id. 另外,您可能不应该为一个ID拥有多个值。 You may wish to consider something like this: 您不妨考虑这样的事情:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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