簡體   English   中英

如何使用stax解析器將屬性附加到現有xml

[英]How to append an attribute to an existing xml using stax parser

我想使用stax parse將屬性附加到現有xml。 請提出建議。

以下是我需要添加的摘錄代碼。

<un:UtranCell id="RNC17-1-1">

追加后的樣子如下

<un:UtranCell id="RNC17-1-1" modifier="delete">

以下是我嘗試過的片段代碼。 但是我無法添加屬性

try {               
      File fXmlFile = new File("/home/xgeoraj/bcgImportFiles/imports/UtranCell.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
      NodeList nList = doc.getElementsByTagName("un:UtranCell");
      for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        System.out.println("\nCurrent Element :" + nNode.getNodeName());
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
          Element eElement = (Element) nNode;
          System.out.println("UtranCell id is: " + eElement.getAttribute("id"));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
}

以下是我需要在其中添加的XML文件。

<?xml version="1.0" encoding="UTF-8"?>
<bulkCmConfigDataFile xmlns:un="utranNrm.xsd" xmlns:xn="genericNrm.xsd" xmlns:gn="geranNrm.xsd" xmlns="configData.xsd" xmlns:es="EricssonSpecificAttributes.14.02.xsd">
    <fileHeader fileFormatVersion="32.615 V4.5" vendorName="Ericsson"/>
    <configData dnPrefix="Undefined">
        <xn:SubNetwork id="ONRM_ROOT_MO_R">
            <xn:SubNetwork id="RNC17">
                <xn:MeContext id="RNC17">
                    <xn:ManagedElement id="1">
                        <un:RncFunction id="1">
                            <un:UtranCell id="RNC17-1-1" modifier="delete">

我認為您想要做的就是將屬性添加到檢索到的元素中,方法是設置一個元素。 取出if語句。

if (nNode.getNodeType() == Node.ELEMENT_NODE) {
    Element eElement = (Element) nNode;
    System.out.println("UtranCell id is: " + eElement.getAttribute("id"));
    eElement.setAttribute("modifier", "delete"); // <-- This is the added line
}

有關參考,請參見javadoc中的Element

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM