實例講述在Java程序利用JDom解析和傳遞XML格式數據

 Java利用JDom來解析處理XML數據格式:node

  須要的包jdom-1.1.2.jar服務器

  1 將數據轉換成XML格式的數據進行傳遞dom

  Element rootList, firstList, secondItem, thirdItem;ide

  //根元素標籤名ui

  rootList = new Element("root");xml

  //根元素標籤內的屬性名與值對象

  rootList.setAttribute("project", pname);ip

  //生成Doc文檔文檔

  Document Doc = new Document(rootList);字符串

  //獲取文檔中的根標籤

  rootList = Doc.getRootElement();

  for (int i = 0; i < judges.size(); i++)

  {

  //生成新的元素

  firstList = new Element("flayout");

  firstList.setAttribute("percent", "percent");

  //加入根級元素中

  rootList.addContent(firstList);

  }

  XMLOutputter XMLOut = new XMLOutputter();

//將doc文檔轉換爲字符串型的XML格式

  String xmlinfo = XMLOut.outputString(Doc);

  //將開頭的去掉

  xmlinfo = xmlinfo.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>",

  "");

  //返回已經封裝好的XML數據

  return xmlinfo;

  2 將字符串中的XML解析出進行處理

  //建立一個新的字符串

  StringReader read = new StringReader(stadXML);

  // 建立新的輸入源SAX 解析器將使用 InputSource 對象來肯定如何讀取 XML 輸入

  InputSource source = new InputSource(read);

  // 建立一個新的SAXBuilder

  SAXBuilder sb = new SAXBuilder();

  String projectName;

  List<Judgestandard> standIndex = new ArrayList<Judgestandard>();

  try {

  // 經過輸入源構造一個Document

  Document doc = sb.build(source);

  // 取的根元素

  Element root = doc.getRootElement();

  projectName = root.getAttributeValue("project");

  // 獲得根元素全部子元素的集合

  Element et = null;

  List nodes = root.getChildren();

  // 第一級指標

  for (int i = 0; i < nodes.size(); i++) {

  et = (Element) nodes.get(i);// 循環依次獲得子元素

  Judgestandard judge = new Judgestandard();

  //獲取該元素中屬性的值

  String fid = et.getAttributeValue("mainid");

  //獲取元素的孩子數目

  List fsize = et.getChildren();

  // 第二級指標

  for (int j = 0; j < fsize.size(); j++)

  {

  et = (Element) fsize.get(j);// 循環依次獲得子元素

  et.getAttributeValue("stdid")

  }

  Java處理XML文檔

  不須要包

  待處理的XML文檔:

  <?xml version="1.0" encoding="ISO-8859-1"?>

  <root>

  <ip>localhost</ip>

  <port>8080</port>

  </root>

  static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  static DocumentBuilder builder = null;

  builder = factory .newDocumentBuilder();

  //獲取服務器根目錄地址

  Document document = builder.parse(new File("src/ip.xml"));

  Element rootElement = document.getDocumentElement();

  NodeList list1 = rootElement.getElementsByTagName("ip");

  NodeList list2 = rootElement.getElementsByTagName("port");

  Element ip = (Element) list1.item(0);

  Element port = (Element) list2.item(0);

  String s =ip.getFirstChild()。getNodeValue()。toString()+":"+port.getFirstChild()。getNodeValue()。toString();

  System.out.println(s);

相關文章
相關標籤/搜索