2015-05-26 24 views
0

我試圖讀取XML文檔的一些INT:如何分析包含許多整數字符串

<aaa> 
    <agent> 
     <name>Agent 1</name> 
     <position>4 5</position> 
     <vector>87 78 54 5 -4</vector> 
    </agent> 
</aaa> 

這是我的Java代碼:

DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); 

DocumentBuilder builder = documentFactory.newDocumentBuilder(); 
Document document = builder.parse(new File("utility.xml")); 

NodeList agents = document.getElementsByTagName("agent"); 

for(int i=0; i<agents.getLength(); i++) { 
     Node node = agents.item(i); 

     if(node.getNodeType() == Node.ELEMENT_NODE) { 
       Element agente = (Element)node; 

       String name = agente.getElementsByTagName("name").item(0).getFirstChild().getNodeValue(); 
       String position = agente.getElementsByTagName("position").item(0).getFirstChild().getNodeValue(); 
       String vector = agente.getElementsByTagName("vector").item(0).getFirstChild().getNodeValue(); 

我想解析字符串位置爲2整數(4和5),我想將字符串向量解析爲5整數(並將它們放入數組中)。 我該怎麼辦?感謝您的時間!

回答

0

你可以使用一個Scanner並讀取String內容通過nextInt

String stringRead = ...; //imagine you read <position> here 
Scanner scanner = new Scanner(stringRead); 
List<Integer> intList = new ArrayList<>(); 
while (scanner.hasNext()) { 
    intList.add(scanner.nextInt()); 
} 

如果使用Java 8,那麼你可以把它縮短了由使用流的力量:

String stringRead = ...; //imagine you read <position> here 
List<Integer> intList = Arrays.stream(stringRead.split("\\s+")) 
    .map(x -> Integer.valueOf(x)) 
    .collect(Collectors.toList()); 
0

轉換爲int的邏輯[]

public static void main(String args[]) { 
    String position ="87 78 54 5 -4"; 
    String vector = "4 5"; 

    String[] posArr = position.split(" "); 
    int[] positionArray = new int[posArr.length]; 

    for(int i = 0 ; i < posArr.length ; i ++) { 
     positionArray[i] = Integer.parseInt(posArr[i]); 
    } 

    String[] vectArr = vector.split(" "); 
    int[] vectorArray = new int[vectArr.length]; 
    for(int i = 0 ; i < vectArr.length ; i ++) { 
     vectorArray[i] = Integer.parseInt(vectArr[i]); 
    } 
} 
相關問題