2015-02-23 50 views
0

如何轉換Java以下的標籤,我認爲使用XTreams Framework如何轉換Java中的標籤

幫幫我!我在Google搜索中看到。

<?xml version="1.0" encoding="ISO-8859-1"?> 
<fastbranch-xe-request project="Tech" transaction-id="massiveSelectBranchList_By_Institution_Facade" transaction-version="1.0"> 
    <entity name="glb.credential"> 
     <attribute name="channelId">8</attribute> 
     <attribute name="originBranchId">0</attribute> 
     <attribute name="dependencyId">1000</attribute> 
    </entity> 
    <entity id="Institution" name="in.institution"> 
     <attribute name="institutionId">1111</attribute> 
    </entity> </fastbranch-xe-request> 

對於這個

<?xml version="1.0" encoding="ISO-8859-1"?> 
<massiveSelectBranchList_By_Institution_Facade> 
    <credential> 
     <channelId>8</channelId> 
     <originBranchId>0</originBranchId> 
     <dependencyId>1000</dependencyId> 
    </credential> 
    <institution> 
     <institutionId>1111</institutionId> 
    </institution> 
</massiveSelectBranchList_By_Institution_Facade> 

回答

1

我使用DOM改造初始請求的第二reineke的建議。以下是您解析初始請求的開端:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
Document doc = dBuilder.parse("xml"); 

// optional, but recommended 
// read this - 
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work 
doc.getDocumentElement().normalize(); 

// System.out.println("Root element :" + 
// doc.getDocumentElement().getNodeName()); 

// This breaks the document apart by the specified tag 
NodeList nList = doc.getElementsByTagName("fastbranch-xe-request"); 

// For each instance of the "fastbranch-xe-request" tag... 
for (int pos = 0; pos < nList.getLength(); pos++) { 
    Node nNode = nList.item(pos); 

    if (nNode.getNodeType() == Node.ELEMENT_NODE) { 

     Element eElement = (Element) nNode; 

     // This gets you: "massiveSelectBranchList_By_Institution_Facade" 
     String transactionID = eElement.getAttribute("transaction-id"); 

     // This gets you: "glb.credential" 
     String entityName = eElement.getElementsByTagName("entity").item(0). 
       getAttributes().getNamedItem("name").toString(); 

     // Continue this until you've pulled the tag names from each 
     // "attribute" tag. Once you've pulled all the names (and parsed 
     // the values as well), you can use DOM to construct the second 
     // XML request. 
    } 
} 
+0

感謝您的回答! – WhoAre 2015-02-28 23:06:44

+0

很高興幫助!讓我知道是否需要幫助解析值或在您解析出信息後編寫新的XML;我剛剛完成了一個大型項目,完全按照您所描述的內容進行。 – roflplanes 2015-03-02 23:29:22

0

我不知道該XTreams框架。在Java中,通常選擇SAX或DOM進行XML解析。

一個簡單的例子: http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

或一個很好的教程:http://howtodoinjava.com/2014/07/31/java-xml-dom-parser-example-tutorial/

只是爲了讓你在正確的方向。如果您在應用本教程時遇到困難,請告訴您目前爲止的情況,並且我很樂意提供幫助。

如果您不被綁定到java,您可以考慮使用java的XSLT instad。它特別爲此類任務而製作,並且更短,更容易。

希望我能幫助 reineke