1. 程式人生 > >Java對XML屬性解析功能

Java對XML屬性解析功能

rgs dom pack text clas oid set sage todo

package usi.ipms.test;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class ParseCasXmlString {
public static void main(String[] args) {
String XmlString="<?xml version=\"1.0\" encoding=\"utf-8\"?>"+

"<AuthenChallengeMsg>"+
"<MessageType type=\"7\">"+
"</MessageType>"+
"<Protocol version=\"2.1\"></Protocol>"+
"<ID name=\"\"></ID>"+
"<params></params>"+
"<SessionID sessionid=\"bd08417d-5a1a-4ca1\"></SessionID>"+
"<Challenges>"+
"<DynamicPwdChallenge authenNumber=\"1\" minPwdSize=\"0\" authenMode=\"smscha\" allowBeginTime=\"\" allowEndTime=\"\" type=\"casbox\" isAllowTime=\"AllowTime\" allowMaxTime=\"6\" applyReason=\"\" challenge=\"d2FuZ3RhbyznjvmtpssMTczOTgzOTI4OTIsMEBAbWFsb25nLOmprOm+mSwxNzM5ODM5Mjg5MiwwQEB6aGuZ2h5OW8oOa1t+awuCwxNzc1NjA5MzAzNSww\">"+
"</DynamicPwdChallenge>"+
"</Challenges>"+
"</AuthenChallengeMsg>";

try {
    Document document  = DocumentHelper.parseText(XmlString);
    //獲取根節點元素,此處為<AuthenChallengeMsg>
    Element node = document.getRootElement();
    //通過element()獲得指定節點名稱的節點,在這裏是<SessionID>
    Element SessionID = node.element("SessionID");
    //獲得所在節點的節點名稱
    String elementName = SessionID.getName();
    //獲取<西遊記>節點所具有的屬性,輸入需要的屬性名稱id
    Attribute attribute = SessionID.attribute("sessionid");
    //獲得屬性文本 x001
    String txt = attribute.getText();
    System.out.println("SessionID:"+SessionID);
    System.out.println("elementName:"+elementName);
    System.out.println("attribute:"+attribute);
    System.out.println("txt:"+txt);
} catch (DocumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

}
}

Java對XML屬性解析功能