2011-10-06 174 views
0

我想解析我的Document對象,就像;解析Document對象時遇到困難?

<message> 
<header> 
<messageType>snmp</messageType> 
<sendFrom>localhost</sendFrom> 
<hostName>localhost</hostName> 
<sendTo>192.168.0.15</sendTo> 
<receiverName>receiverHost</receiverName> 
<date>06/10/2011 17:34:55</date> 
</header> 
<body> 
<snmpType>set</snmpType> 
<ip>127.0.0.1</ip> 
<community>public</community> 
<variables> 
    <variableBinding> 
    <variable>TechDive.in</variable> 
    <OID>1.3.6.1.4.1.8072.3.2.10</OID> 
    </variableBinding> 
    <variableBinding> 
    <variable>TechDive.in</variable> 
    <OID>1.3.6.1.4.1.8072.3.2.10</OID> 
    </variableBinding> 
    <variableBinding> 
    <variable>TechDive.in</variable> 
    <OID>1.3.6.1.4.1.8072.3.2.10</OID> 
    </variableBinding> 
    <variableBinding> 
    <variable>TechDive.in</variable> 
    <OID>1.3.6.1.4.1.8072.3.2.10</OID> 
    </variableBinding> 
    </variables> 
    </body> 
</message> 

我想所有關閉<variableBinding> S的是下<variables>,我真的會被卡住它,因爲我在XML解析一個小白。

我想寫一個函數是;

public Vector<VariableBinding> getVariables(Document document){ 

    Vector<VariableBinding> variables = new Vector<VariableBinding>(); 

    Element root = document.getRootElement(); 
    Element body = root.getChild("body"); 
    Element oidsElement = body.getChild("variables"); 
    Element variable = oidsElement.getChild("variable"); 

    for (Object currentOidObj : variable.getChildren()) { 

     Element currentOid = (Element) currentOidObj; 
     String oid = currentOid.getText(); 
     Element currentVariable = (Element) currentOidObj; 

     Variable var = new OctetString(currentVariable.getText()); 
     OID oidObj = new OID(oid); 

     VariableBinding v = new VariableBinding(oidObj,var); 
     variables.add(v); 
    } 
    return variables; 
} 

你能幫我拿<variableBinding>嗎?

謝謝大家

回答

2

你需要做的事情喜歡這個:

public Vector<VariableBinding> getVariables(Document document){ 

Vector<VariableBinding> variables = new Vector<VariableBinding>(); 

Element root = document.getRootElement(); 
Element body = root.getChild("body"); 
Element oidsElement = body.getChild("variables"); 

for (Object ovb: oidsElement.getChildren("variableBinding")) { 

    Element vb = (Element) ovb; 
    Variable var = new OctetString(vb.getChild("OID").getText()); 
    OID oidObj = new OID(vb.getChild("variable").getText()); 

    VariableBinding v = new VariableBinding(oidObj,var); 
    variables.add(v); 
} 
return variables; 
} 
4

你有使用XPath考慮?

//variableBinding將選擇所有的變量綁定元素。

例如爲:

XPathFactory factory = XPathFactory.newInstance(); 
XPath xpath = factory.newXPath(); 
XPathExpression expr = xpath.compile("//variableBinding"); 

Object result = expr.evaluate(doc, XPathConstants.NODESET); 

NodeList nodes = (NodeList) result; 
for (int i = 0; i < nodes.getLength(); i++) { 
    ... 
} 
+2

我畏縮每次我看到有人暴力破解他們的方式通過XML時間;讓我瘋狂! –