JAVA DOM解析XML

来源:互联网 发布:怎么修复u盘里的数据 编辑:程序博客网 时间:2024/06/05 11:11

xml文件如下:

  1. <smil xmlns="http://www.w3.org/2000/SMIL20/CR/Language">
  2. <head>
  3. <layout>
  4. <root-layout height="100%" width="100%" />
  5. <region id="Image" top="0" left="0" height="80%" width="100%"/>
  6. <region id="Text" top="80%" left="0" height="20%" width="100%"/>
  7. </layout>
  8. </head>
  9. <body>
  10. <par dur = "5000ms">
  11. <img region="Image" src="/contentlib/32/35/92/52.jpg"/>
  12. <audio src="/contentlib/32/36/58.wav"/>
  13. <text region="Text" src="/contentlib/1/3/29/12.txt"/>
  14. </par>
  15. </body>
  16. </smil>

要解析出xml文件节点属性,比如 要得出 节点<img region="Image" src="/contentlib/32/35/92/52.jpg"/> 属性src的值(/contentlib/32/35/92/52.jpg)。

下面是源码,可以直接解析xml文件 ,和文件流。

可以得到节点值,节点属性值,(如果存在多个<img  下面代码还存在问题)

 

  1. import java.io.InputStream;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import javax.xml.parsers.DocumentBuilderFactory;
  5. import javax.xml.parsers.DocumentBuilder;
  6. import javax.xml.parsers.ParserConfigurationException;
  7. import javax.xml.parsers.FactoryConfigurationError;
  8. import org.w3c.dom.Document;
  9. import org.w3c.dom.Element;
  10. import org.w3c.dom.NamedNodeMap;
  11. import org.w3c.dom.NodeList;
  12. import org.w3c.dom.Node;
  13. import org.xml.sax.SAXException;
  14. /**
  15.  * <p>Description:  xml解析类</p>
  16.  *
  17.  */
  18. public class XmlParser
  19. {
  20.     
  21.     private static DocumentBuilderFactory factory;
  22.     private static DocumentBuilder builder;
  23.     private Document doc;
  24.     private Element root;
  25.     private String fileName;
  26.     private InputStream inputstream;
  27.     /**
  28.      * 解析文件xml
  29.      * @param file String
  30.      */
  31.     public XmlParser(String file)
  32.     {
  33.         if (file == null)
  34.         {
  35.             return;
  36.         }
  37.         this.fileName = file;
  38.         try
  39.         {
  40.             load();
  41.         }
  42.         catch (IOException ex)
  43.         {
  44.             ex.printStackTrace();
  45.             return;
  46.         }
  47.     }
  48.     /**
  49.      * 解析输入流xml
  50.      * @param input InputStream
  51.      */
  52.     public XmlParser(InputStream input)
  53.     {
  54.         if (input == null)
  55.         {
  56.             return;
  57.         }
  58.         inputstream = input;
  59.         try
  60.         {
  61.             loadStream();
  62.         }
  63.         catch (IOException ex)
  64.         {
  65.             ex.printStackTrace();
  66.             return;
  67.         }
  68.     }
  69.     /**
  70.      * 获取XML文件中指定标签所对应的节点集合
  71.      * @param key String 标签名字
  72.      * @return ArrayList 指定标签对应的节点集
  73.      */
  74.     public ArrayList findNodes(String key)
  75.     {
  76.         NodeList nodes = root.getElementsByTagName(key);
  77.         ArrayList nodeList = new ArrayList();
  78.         for (int i = 0; i < nodes.getLength(); i++)
  79.         {
  80.             nodeList.add(i, (Node) nodes.item(i));
  81.         }
  82.         return nodeList;
  83.     }
  84.     /**
  85.      * 初始化XML
  86.      * @throws IOException
  87.      */
  88.     public void loadStream()
  89.             throws IOException
  90.     {
  91.         try
  92.         {
  93.             loadXMLParser();
  94.             doc = builder.parse(inputstream);
  95.             root = doc.getDocumentElement();
  96.         }
  97.         catch (IOException ex)
  98.         {
  99.             ex.printStackTrace();
  100.         }
  101.         catch (SAXException ex)
  102.         {
  103.             ex.printStackTrace();
  104.         }
  105.         finally
  106.         {
  107.             inputstream.close();
  108.         }
  109.     }
  110.     /**
  111.      * 初始化XML
  112.      * @throws IOException
  113.      */
  114.     public void load()
  115.             throws IOException
  116.     {
  117.         try
  118.         {
  119.             loadXMLParser();
  120.             doc = builder.parse(fileName);
  121.             root = doc.getDocumentElement();
  122.         }
  123.         catch (SAXException SaxEx)
  124.         {
  125.             SaxEx.printStackTrace();
  126.             throw new IOException(SaxEx.getMessage() + "XML file parse error:"
  127.                                   + SaxEx.getException());
  128.         }
  129.         catch (IOException IoEx)
  130.         {
  131.             IoEx.printStackTrace();
  132.             throw new IOException(IoEx.getMessage() + "XML file parse error:");
  133.         }
  134.         catch (Exception ex)
  135.         {
  136.             ex.printStackTrace();
  137.             throw new IOException(ex.getMessage() + "XML file parse error:");
  138.         }
  139.     }
  140.     /**
  141.      * 初始化XML
  142.      * @throws IOException
  143.      */
  144.     private void loadXMLParser()
  145.             throws IOException
  146.     {
  147.         if (builder == null)
  148.         {
  149.             try
  150.             {
  151.                 factory = DocumentBuilderFactory.newInstance();
  152.                 builder = factory.newDocumentBuilder();
  153.             }
  154.             catch (ParserConfigurationException ex)
  155.             {
  156.                 throw new IOException("XML Parser load error:"
  157.                                       + ex.getLocalizedMessage());
  158.             }
  159.             catch (FactoryConfigurationError ConfErrEx)
  160.             {
  161.                 throw new IOException("XML Parser load error:"
  162.                                       + ConfErrEx.getLocalizedMessage());
  163.             }
  164.             catch (Exception Ex)
  165.             {
  166.                 throw new IOException("XML Parser load error:"
  167.                                       + Ex.getLocalizedMessage());
  168.             }
  169.         }
  170.     }
  171.     /**
  172.      * 获取XML文件中某级节点下一级元素的值
  173.      * @param node 节点对象
  174.      * @param subTagName subTagName元素的标签名
  175.      * @return String 该标记元素的的内容
  176.      */
  177.     public static String getSubTagValue(Node node, String subTagName)
  178.     {
  179.         String returnString = "";
  180.         if ((node != null) && (subTagName != null))
  181.         {
  182.             NodeList children = node.getChildNodes();
  183.             for (int innerLoop = 0; innerLoop < children.getLength(); innerLoop++)
  184.             {
  185.                 Node child = children.item(innerLoop);
  186.                 if ((child != null) && (child.getNodeName() != null)
  187.                     && (child.getNodeName().equals(subTagName)))
  188.                 {
  189.                     Node grandChild = child.getFirstChild();
  190.                     if (grandChild != null)
  191.                     {
  192.                         return grandChild.getNodeValue();
  193.                     }
  194.                 }
  195.             }
  196.         }
  197.         return returnString;
  198.     }
  199.     /**
  200.      * 获取XML文件中某单一值
  201.      * @param node 节点对象
  202.      * @param subTagName subTagName元素的标签名
  203.      * @return String 该标记元素的的内容
  204.      */
  205.     public String getresult(String name)
  206.     {
  207.         String result = "";
  208.         ArrayList resultlist = findNodes(name);
  209.         if ((resultlist != null) && (resultlist.size() > 0))
  210.         {
  211.             for (int i = 0; i < resultlist.size(); i++)
  212.             {
  213.                 Node node = (Node) resultlist.get(i);
  214.                 if (node instanceof Element)
  215.                 {
  216.                     if ((node != null) && (node.getNodeName() != null)
  217.                         && (node.getNodeName().equals(name)))
  218.                     {
  219.                         Node grandChild = node.getFirstChild();
  220.                         if (grandChild != null)
  221.                         {
  222.                             result = grandChild.getNodeValue();
  223.                         }
  224.                     }
  225.                 }
  226.             }
  227.         }
  228.         return result;
  229.     }
  230.     
  231.     //
  232.     public String getAttr(String name,String attrName)
  233.     {
  234.         String result = "";
  235.         ArrayList resultlist = findNodes(name);
  236.         if ((resultlist != null) && (resultlist.size() > 0))
  237.         {
  238.             for (int i = 0; i < resultlist.size(); i++)
  239.             {
  240.                 Node node = (Node) resultlist.get(i);
  241.                 if (node instanceof Element)
  242.                 {
  243.                     if ((node != null) && (node.getNodeName() != null)
  244.                         && (node.getNodeName().equals(name)))
  245.                     {
  246.                         //遍历整个xml某节点指定的属性
  247.                         NamedNodeMap attrs=node.getAttributes();
  248.                         if(attrs.getLength()>0 && attrs!=null)
  249.                         {
  250.                             Node attr=attrs.getNamedItem(attrName);
  251.                             result=attr.getNodeValue();
  252.                 
  253.                         }
  254.                         
  255.                     }
  256.                 }
  257.             }
  258.         }
  259.         return result;
  260.     }
  261.     
  262.     public static void main(String[] args)
  263.     {
  264.         String file="D://common//Tomcat60//smil.smil";
  265.   
  266.         XmlParser xml =new XmlParser(file);
  267.         System.out.println(xml.getAttr("text","src"));
  268.   
  269.     }
  270. }

 

解决多个节点问题,,比如下面的xml文件

  1. <smil xmlns="http://www.w3.org/2000/SMIL20/CR/Language">
  2. <head>
  3. <layout>
  4. <root-layout height="100%" width="100%" />
  5. <region id="Image" top="0" left="0" height="80%" width="100%"/>
  6. <region id="Text" top="80%" left="0" height="20%" width="100%"/>
  7. </layout>
  8. </head>
  9. <body>
  10. <par dur = "5000ms">
  11. <img region="Image" src="/contentlib/5/6/95/0.jpg"/>
  12. <audio src="/contentlib/5/6/95/0.wav"/>
  13. <text region="Text" src="/contentlib/5/6/95/0.txt"/>
  14. </par>
  15. <par dur = "5000ms">
  16. <img region="Image" src="/contentlib/5/6/95/1.gif"/>
  17. <audio src="/contentlib/5/6/95/1.wav"/>
  18. <text region="Text" src="/contentlib/5/6/95/1.txt"/>
  19. </par>
  20. <par dur = "5000ms">
  21. <img region="Image" src="/contentlib/5/6/95/2.gif"/>
  22. <audio src="/contentlib/5/6/95/2.wav"/>
  23. <text region="Text" src="/contentlib/5/6/95/2.txt"/>
  24. </par>
  25. </body>
  26. </smil>

要得出所有的src值,下面代码可以实现

 

  1. import java.io.InputStream;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.LinkedList;
  5. import java.util.List;
  6. import javax.xml.parsers.DocumentBuilderFactory;
  7. import javax.xml.parsers.DocumentBuilder;
  8. import javax.xml.parsers.ParserConfigurationException;
  9. import javax.xml.parsers.FactoryConfigurationError;
  10. import org.w3c.dom.Document;
  11. import org.w3c.dom.Element;
  12. import org.w3c.dom.NamedNodeMap;
  13. import org.w3c.dom.NodeList;
  14. import org.w3c.dom.Node;
  15. import org.xml.sax.SAXException;
  16. /**
  17.  * Description:  xml解析类
  18.  * @author wayfoon
  19.  * @version 
  20.  */
  21. public class XmlParser
  22. {
  23.     private static DocumentBuilderFactory factory;
  24.     private static DocumentBuilder builder;
  25.     private Document doc;
  26.     private Element root;
  27.     private String fileName;
  28.     private InputStream inputstream;
  29.     /**
  30.      * 解析文件xml
  31.      * @param file
  32.      *            String
  33.      */
  34.     public XmlParser(String file)
  35.     {
  36.         if (file == null)
  37.         {
  38.             return;
  39.         }
  40.         this.fileName = file;
  41.         try
  42.         {
  43.             load();
  44.         }
  45.         catch (IOException ex)
  46.         {
  47.             ex.printStackTrace();
  48.             return;
  49.         }
  50.     }
  51.     /**
  52.      * 解析输入流xml
  53.      * 
  54.      * @param input
  55.      *            InputStream
  56.      */
  57.     public XmlParser(InputStream input)
  58.     {
  59.         if (input == null)
  60.         {
  61.             return;
  62.         }
  63.         inputstream = input;
  64.         try
  65.         {
  66.             loadStream();
  67.         }
  68.         catch (IOException ex)
  69.         {
  70.             ex.printStackTrace();
  71.             return;
  72.         }
  73.     }
  74.     /**
  75.      * 获取XML文件中指定标签所对应的节点集合
  76.      * 
  77.      * @param key
  78.      *            String 标签名字
  79.      * @return ArrayList 指定标签对应的节点集
  80.      */
  81.     public ArrayList findNodes(String key)
  82.     {
  83.         NodeList nodes = root.getElementsByTagName(key);
  84.         ArrayList nodeList = new ArrayList();
  85.         for (int i = 0; i < nodes.getLength(); i++)
  86.         {
  87.             nodeList.add(i, (Node) nodes.item(i));
  88.         }
  89.         return nodeList;
  90.     }
  91.     /**
  92.      * 初始化XML
  93.      * 
  94.      * @throws IOException
  95.      */
  96.     public void loadStream() throws IOException
  97.     {
  98.         try
  99.         {
  100.             loadXMLParser();
  101.             doc = builder.parse(inputstream);
  102.             root = doc.getDocumentElement();
  103.         }
  104.         catch (IOException ex)
  105.         {
  106.             ex.printStackTrace();
  107.         }
  108.         catch (SAXException ex)
  109.         {
  110.             ex.printStackTrace();
  111.         }
  112.         finally
  113.         {
  114.             inputstream.close();
  115.         }
  116.     }
  117.     /**
  118.      * 初始化XML
  119.      * 
  120.      * @throws IOException
  121.      */
  122.     public void load() throws IOException
  123.     {
  124.         try
  125.         {
  126.             loadXMLParser();
  127.             doc = builder.parse(fileName);
  128.             root = doc.getDocumentElement();
  129.         }
  130.         catch (SAXException SaxEx)
  131.         {
  132.             SaxEx.printStackTrace();
  133.             throw new IOException(SaxEx.getMessage() + "XML file parse error:"
  134.                     + SaxEx.getException());
  135.         }
  136.         catch (IOException IoEx)
  137.         {
  138.             IoEx.printStackTrace();
  139.             throw new IOException(IoEx.getMessage() + "XML file parse error:");
  140.         }
  141.         catch (Exception ex)
  142.         {
  143.             ex.printStackTrace();
  144.             throw new IOException(ex.getMessage() + "XML file parse error:");
  145.         }
  146.     }
  147.     /**
  148.      * 初始化XML
  149.      * 
  150.      * @throws IOException
  151.      */
  152.     private void loadXMLParser() throws IOException
  153.     {
  154.         if (builder == null)
  155.         {
  156.             try
  157.             {
  158.                 factory = DocumentBuilderFactory.newInstance();
  159.                 builder = factory.newDocumentBuilder();
  160.             }
  161.             catch (ParserConfigurationException ex)
  162.             {
  163.                 throw new IOException("XML Parser load error:"
  164.                         + ex.getLocalizedMessage());
  165.             }
  166.             catch (FactoryConfigurationError ConfErrEx)
  167.             {
  168.                 throw new IOException("XML Parser load error:"
  169.                         + ConfErrEx.getLocalizedMessage());
  170.             }
  171.             catch (Exception Ex)
  172.             {
  173.                 throw new IOException("XML Parser load error:"
  174.                         + Ex.getLocalizedMessage());
  175.             }
  176.         }
  177.     }
  178.     /**
  179.      * 获取XML文件中某级节点下一级元素的值
  180.      * 
  181.      * @param node
  182.      *            节点对象
  183.      * @param subTagName
  184.      *            subTagName元素的标签名
  185.      * @return String 该标记元素的的内容
  186.      */
  187.     public static String getSubTagValue(Node node, String subTagName)
  188.     {
  189.         String returnString = "";
  190.         if ((node != null) && (subTagName != null))
  191.         {
  192.             NodeList children = node.getChildNodes();
  193.             for (int innerLoop = 0; innerLoop < children.getLength(); innerLoop++)
  194.             {
  195.                 Node child = children.item(innerLoop);
  196.                 if ((child != null) && (child.getNodeName() != null)
  197.                         && (child.getNodeName().equals(subTagName)))
  198.                 {
  199.                     Node grandChild = child.getFirstChild();
  200.                     if (grandChild != null)
  201.                     {
  202.                         return grandChild.getNodeValue();
  203.                     }
  204.                 }
  205.             }
  206.         }
  207.         return returnString;
  208.     }
  209.     /**
  210.      * 获取XML文件中某单一值
  211.      * 
  212.      * @param node
  213.      *            节点对象
  214.      * @param subTagName
  215.      *            subTagName元素的标签名
  216.      * @return String 该标记元素的的内容
  217.      */
  218.     public String getresult(String name)
  219.     {
  220.         String result = "";
  221.         ArrayList resultlist = findNodes(name);
  222.         if ((resultlist != null) && (resultlist.size() > 0))
  223.         {
  224.             for (int i = 0; i < resultlist.size(); i++)
  225.             {
  226.                 Node node = (Node) resultlist.get(i);
  227.                 if (node instanceof Element)
  228.                 {
  229.                     if ((node != null) && (node.getNodeName() != null)
  230.                             && (node.getNodeName().equals(name)))
  231.                     {
  232.                         Node grandChild = node.getFirstChild();
  233.                         if (grandChild != null)
  234.                         {
  235.                             result = grandChild.getNodeValue();
  236.                         }
  237.                     }
  238.                 }
  239.             }
  240.         }
  241.         return result;
  242.     }
  243.     /**
  244.      * 得到某一节点指定属性的值
  245.      * @param node
  246.      * @param name
  247.      * @param attrName
  248.      * @return
  249.      */
  250.     public String getAttrByNode(Node node, String name, String attrName)
  251.     {
  252.         NodeList list = node.getChildNodes();
  253.         // System.out.println("---"+list.getLength());
  254.         String result = "";
  255.         Node child = null;
  256.         for (int innerLoop = 0; innerLoop < list.getLength(); innerLoop++)
  257.         {
  258.             child = list.item(innerLoop);
  259.             if (child instanceof Element)
  260.             {
  261.                 if ((child != null) && (child.getNodeName() != null)
  262.                         && (child.getNodeName().equals(name)))
  263.                 {
  264.                     // 遍历整个xml某节点指定的属性
  265.                     NamedNodeMap attrs = child.getAttributes();
  266.                     if (attrs.getLength() > 0 && attrs != null)
  267.                     {
  268.                         Node attr = attrs.getNamedItem(attrName);
  269.                         result = attr.getNodeValue();
  270.                     }
  271.                 }
  272.             }
  273.         }
  274.         return result;
  275.     }
  276.     /**
  277.      * 得到节点属性值,节点可能存在多个,返回的是个数组
  278.      * 
  279.      * @param name
  280.      * @param attrName
  281.      * @return
  282.      */
  283.     public String[] getAttr(String name, String attrName)
  284.     {
  285.         int len = 0;
  286.         String result[] = new String[] {};
  287.         ArrayList resultlist = findNodes(name);
  288.         if ((resultlist != null) && (resultlist.size() > 0))
  289.         {
  290.             result = new String[resultlist.size() * 3];
  291.             for (int i = 0; i < resultlist.size(); i++)
  292.             {
  293.                 Node node = (Node) resultlist.get(i);
  294.                 if (node instanceof Element)
  295.                 {
  296.                     if ((node != null) && (node.getNodeName() != null)
  297.                             && (node.getNodeName().equals(name)))
  298.                     {
  299.                         String img = getAttrByNode(node, "img""src");
  300.                         String audio = getAttrByNode(node, "audio""src");
  301.                         String text = getAttrByNode(node, "text""src");
  302.                         if (!"".equals(img) && img != null)
  303.                         {
  304.                             result[len++] = img;
  305.                         }
  306.                         else
  307.                         {
  308.                             result[len++] = "";
  309.                         }
  310.                         if (!"".equals(audio) && audio != null)
  311.                         {
  312.                             result[len++] = audio;
  313.                         }
  314.                         else
  315.                         {
  316.                             result[len++] = "";
  317.                         }
  318.                         if (!"".equals(text) && text != null)
  319.                         {
  320.                             result[len++] = text;
  321.                         }
  322.                         else
  323.                         {
  324.                             result[len++] = "";
  325.                         }
  326.                         // System.out.println(result[len]);
  327.                     }
  328.                 }
  329.             }
  330.         }
  331.         //System.out.println(result.length);
  332.         return result;
  333.     }
  334.     public static void main(String[] args)
  335.     {
  336.         String file = "D://**//smil.smil";
  337.         XmlParser xml = new XmlParser(file);
  338.         // XmlParser xml1 =new XmlParser(file1);
  339.         String[] strings = xml.getAttr("par""dur");
  340.         for (int i = 0; i < strings.length; i++)
  341.         {
  342.             System.out.println(strings[i]);
  343.         }
  344.     }
  345. }

输入结果:就是我们想得到的

0 0
原创粉丝点击