XML字符串的读取

单纯的一个例子,看了就懂了,找了一个上午啊~泪流满面。。。

package aaa;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class xmlread
{
   public static void main(String[] args){

      String xmlStr = "<int xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">1</int>";
              try
              {
                  DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance();
                  DocumentBuilder builder = factory.newDocumentBuilder(); 
                  Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));
                  Element root = doc.getDocumentElement();
                  NodeList optionNodeList = root.getChildNodes();
                  if(optionNodeList!=null)
                  {
                      int totalNode = optionNodeList.getLength();
                      for (int i=0;i<totalNode;i++)
                      {
                          Node optionNode = optionNodeList.item(i);
                          System.out.println(optionNode.getNodeName()+" - "+optionNode.getNodeType()+" - "+optionNode.getNodeValue()+" - "+optionNode.getTextContent());
                      }
                  }
              }
              catch(Exception e)
              {
                  e.printStackTrace();
              }

      }
}

运行结果

#text - 3 - 1 - 1
原文地址:https://www.cnblogs.com/zhidian314/p/2630159.html