简体   繁体   English

如何使用Java在xml中的特定标签内获取子节点?

[英]How to get child nodes within specific tags in xml using java?

Below is an xml File that i have to parse.. 以下是我必须解析的xml文件。

<dataroot>
 <PARM>
   <P1>123</P1>
   <P2>abc</P2>
 </PARM>
 <PARM>
   <P1>456</P1>
   <P2>def</P2>
 </PARM>
 <PARM>
   <P1>789</P1>
   <P2>ghi</P2>
 </PARM>
.......(15times)
</dataroot>

my goal is to get the child nodes (ie p1,p2 not the values inside) and compare those names with a template. 我的目标是获取子节点(即p1,p2而不是内部值),并将这些名称与模板进行比较。

say if p2 is not present i have to append that particular tag to that particular position in the xml file. 说如果p2不存在,我必须将该特定标签附加到xml文件中的特定位置。 The problem is when i use getElementsByTagNames() and store that in an array and then compare it with the template it includes dataroot and PARM as well which i don't want. 问题是当我使用getElementsByTagNames()并将其存储在数组中,然后将其与包含datarootPARM的模板进行比较时,我也不想这样做。

so how can i get just p1 and p2 (for upto 15times) only. 所以我怎么能只得到p1和p2(最多15次)。

For me, the simplest approach would be to use JAXB to unmarshal and marshal, thus adding the missing elements of PARM. 对我而言,最简单的方法是使用JAXB进行封送和封送,从而添加了PARM缺少的元素。 You need to add a few annotations in the classes for dataroot and PARM if the XML element names require different case, but then it's a matter of a few lines of code for unmarshalling and marshalling. 如果XML元素名称要求大小写不同,则需要在datarootPARM的类中添加一些批注,但这仅是几行代码即可进行编组和编组。

@XmlRootElement(name="dataroot")
@XmlType(propOrder = {"parm"})
public class Data {
    @XmlElement(name="PARM")
    private List<Parm> parm = new ArrayList<>();
    public List<Parm> getParm(){ return parm; }
}

@XmlRootElement(name="PARM")
public class Parm {
    private String p1="";
    @XmlElement(name="P1")
    public String getP1(){ return p1; }
    public void setP1( String v ){ p1 = v; }
}

In the same package, add a file jaxb.index containing a single line: 在同一包中,添加包含单行的文件jaxb.index

Data

The main program: 主程序:

JAXBContext jc = JAXBContext.newInstance( PACKAGE ); // dir path
Unmarshaller u = jc.createUnmarshaller();
Data data = (Data)u.unmarshal( new File( XMLIN ) );  // file path
Marshaller m = jc.createMarshaller();
Writer sw = ...;                  // whatever you need
m.marshal( data, sw );

Note the initialisation for field p1 . 注意字段p1的初始化。 This ensures that the element will show up with an empty string. 这样可以确保元素显示为空字符串。 A null results in omitting the element. null将导致省略该元素。

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

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