如何使用节点的名称和特定的属性值来获取特定节点及其子节点?

时间:2015-05-21 21:44:07

标签: java xml parsing xml-parsing

注意:我正在处理我事先不知道其结构的xml文件,因此我无法使用XPath 这是我的xml文件的一个例子:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
<HWData>
<Header time="2013-05-29T13:39:34" uploaded="true" version="1.0" />
  <NE vendorName="Nokia Siemens Networks" NEId="WBTS-431">
    <EQHO vendorName="Nokia Siemens Networks" equipmentHolderId="173" >
        <UNIT vendorName="N" unitId="16" />
        <UNIT vendorName="NOKIA SIEMENS NETWORKS" unitId="225" />
    </EQHO>
    <EQHO vendorName="NSN" equipmentHolderId="40192" >
        <UNIT vendorName="AR" unitId="40267" />
    </EQHO>
  </NE>
  <NE vendorName="Nokia Siemens Networks" NEId="WBTS-261">
    <EQHO vendorName="Nokia Siemens Networks" equipmentHolderId="132" >
      <EQHO vendorName="Nokia Siemens Networks" equipmentHolderId="132-1">
        <UNIT vendorName="NN" unitId="1621" />
      </EQHO>
    </EQHO>
  </NE>
</HWData>

我想知道我是否可以使用例如节点名称&#34; NE&#34;和属性值NEID =&#34; WBTS-261&#34;结果就是这个洞!

结果预期:

<NE vendorName="Nokia Siemens Networks" NEId="WBTS-261">
    <EQHO vendorName="Nokia Siemens Networks" equipmentHolderId="132" >
      <EQHO vendorName="Nokia Siemens Networks" equipmentHolderId="132-1">
        <UNIT vendorName="NN" unitId="1621" />
      </EQHO>
    </EQHO>
</NE>

有人可以让我以正确的方式做任何例子,想法或建议将不胜感激..谢谢

1 个答案:

答案 0 :(得分:1)

将此方法用作字符串:

 public static String NodeToString(String file,String moid) throws   SAXException, IOException, ParserConfigurationException{
String stringNode="";
InputStream in = new ByteArrayInputStream(file.getBytes("ISO-8859-1"));
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
NodeList nodeList = doc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
    if(nodeList.item(i) instanceof Element && ((Element)nodeList.item(i)).getAttribute("MOID").equalsIgnoreCase(moid)){

try
{

  // Set up the output transformer
  TransformerFactory transfac = TransformerFactory.newInstance();
  Transformer trans = transfac.newTransformer();
  trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  trans.setOutputProperty(OutputKeys.INDENT, "yes");

  // Print the DOM node

  StringWriter sw = new StringWriter();
  StreamResult result = new StreamResult(sw);
  DOMSource source = new DOMSource(nodeList.item(i));
  trans.transform(source, result);
  stringNode = sw.toString();

  //System.out.println(xmlString);
}
catch (TransformerException e)
{
  e.printStackTrace();
}       


    }
}
return stringNode;

 }