org.w3c.dom 解析XML檔案 可以解析出節點屬性
阿新 • • 發佈:2019-02-10
xml檔案如下:
- <smilxmlns="http://www.w3.org/2000/SMIL20/CR/Language">
- <head>
- <layout>
- <root-layoutheight="100%"width="100%"/>
- <regionid="Image"top="0"left="0"height="80%"width="100%"/>
- <regionid="Text"top="80%"left="0"height="20%"width="100%"/>
- </layout>
- </head>
- <body>
- <pardur
- <imgregion="Image"src="/contentlib/32/35/92/52.jpg"/>
- <audiosrc="/contentlib/32/36/58.wav"/>
- <textregion="Text"src="/contentlib/1/3/29/12.txt"/>
- </par>
- </body>
- </smil>
要解析出xml檔案節點屬性,比如 要得出 節點<img region="Image" src="/contentlib/32/35/92/52.jpg"/> 屬性src的值(/contentlib/32/35/92/52.jpg)。
下面是原始碼,可以直接解析xml檔案 ,和檔案流。
可以得到節點值,節點屬性值,(如果存在多個<img 下面程式碼還存在問題)
- import java.io.InputStream;
- import java.io.IOException;
- import java.util.ArrayList;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.ParserConfigurationException;
- import javax.xml.parsers.FactoryConfigurationError;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.NamedNodeMap;
- import org.w3c.dom.NodeList;
- import org.w3c.dom.Node;
- import org.xml.sax.SAXException;
- /**
- * <p>Description: xml解析類</p>
- *
- */
- publicclass XmlParser
- {
- privatestatic DocumentBuilderFactory factory;
- privatestatic DocumentBuilder builder;
- private Document doc;
- private Element root;
- private String fileName;
- private InputStream inputstream;
- /**
- * 解析檔案xml
- * @param file String
- */
- public XmlParser(String file)
- {
- if (file == null)
- {
- return;
- }
- this.fileName = file;
- try
- {
- load();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- return;
- }
- }
- /**
- * 解析輸入流xml
- * @param input InputStream
- */
- public XmlParser(InputStream input)
- {
- if (input == null)
- {
- return;
- }
- inputstream = input;
- try
- {
- loadStream();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- return;
- }
- }
- /**
- * 獲取XML檔案中指定標籤所對應的節點集合
- * @param key String 標籤名字
- * @return ArrayList 指定標籤對應的節點集
- */
- public ArrayList findNodes(String key)
- {
- NodeList nodes = root.getElementsByTagName(key);
- ArrayList nodeList = new ArrayList();
- for (int i = 0; i < nodes.getLength(); i++)
- {
- nodeList.add(i, (Node) nodes.item(i));
- }
- return nodeList;
- }
- /**
- * 初始化XML
- * @throws IOException
- */
- publicvoid loadStream()
- throws IOException
- {
- try
- {
- loadXMLParser();
- doc = builder.parse(inputstream);
- root = doc.getDocumentElement();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- }
- catch (SAXException ex)
- {
- ex.printStackTrace();
- }
- finally
- {
- inputstream.close();
- }
- }
- /**
- * 初始化XML
- * @throws IOException
- */
- publicvoid load()
- throws IOException
- {
- try
- {
- loadXMLParser();
- doc = builder.parse(fileName);
- root = doc.getDocumentElement();
- }
- catch (SAXException SaxEx)
- {
- SaxEx.printStackTrace();
- thrownew IOException(SaxEx.getMessage() + "XML file parse error:"
- + SaxEx.getException());
- }
- catch (IOException IoEx)
- {
- IoEx.printStackTrace();
- thrownew IOException(IoEx.getMessage() + "XML file parse error:");
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- thrownew IOException(ex.getMessage() + "XML file parse error:");
- }
- }
- /**
- * 初始化XML
- * @throws IOException
- */
- privatevoid loadXMLParser()
- throws IOException
- {
- if (builder == null)
- {
- try
- {
- factory = DocumentBuilderFactory.newInstance();
- builder = factory.newDocumentBuilder();
- }
- catch (ParserConfigurationException ex)
- {
- thrownew IOException("XML Parser load error:"
- + ex.getLocalizedMessage());
- }
- catch (FactoryConfigurationError ConfErrEx)
- {
- thrownew IOException("XML Parser load error:"
- + ConfErrEx.getLocalizedMessage());
- }
- catch (Exception Ex)
- {
- thrownew IOException("XML Parser load error:"
- + Ex.getLocalizedMessage());
- }
- }
- }
- /**
- * 獲取XML檔案中某級節點下一級元素的值
- * @param node 節點物件
- * @param subTagName subTagName元素的標籤名
- * @return String 該標記元素的的內容
- */
- publicstatic String getSubTagValue(Node node, String subTagName)
- {
- String returnString = "";
- if ((node != null) && (subTagName != null))
- {
- NodeList children = node.getChildNodes();
- for (int innerLoop = 0; innerLoop < children.getLength(); innerLoop++)
- {
- Node child = children.item(innerLoop);
- if ((child != null) && (child.getNodeName() != null)
- && (child.getNodeName().equals(subTagName)))
- {
- Node grandChild = child.getFirstChild();
- if (grandChild != null)
- {
- return grandChild.getNodeValue();
- }
- }
- }
- }
- return returnString;
- }
- /**
- * 獲取XML檔案中某單一值
- * @param node 節點物件
- * @param subTagName subTagName元素的標籤名
- * @return String 該標記元素的的內容
- */
- public String getresult(String name)
- {
- String result = "";
- ArrayList resultlist = findNodes(name);
- if ((resultlist != null) && (resultlist.size() > 0))
- {
- for (int i = 0; i < resultlist.size(); i++)
- {
- Node node = (Node) resultlist.get(i);
- if (node instanceof Element)
- {
- if ((node != null) && (node.getNodeName() != null)
- && (node.getNodeName().equals(name)))
- {
- Node grandChild = node.getFirstChild();
- if (grandChild != null)
- {
- result = grandChild.getNodeValue();
- }
- }
- }
- }
- }
- return result;
- }
- //
- public String getAttr(String name,String attrName)
- {
- String result = "";
- ArrayList resultlist = findNodes(name);
- if ((resultlist != null) && (resultlist.size() > 0))
- {
- for (int i = 0; i < resultlist.size(); i++)
- {
- Node node = (Node) resultlist.get(i);
- if (node instanceof Element)
- {
- if ((node != null) && (node.getNodeName() != null)
- && (node.getNodeName().equals(name)))
- {
- //遍歷整個xml某節點指定的屬性
- NamedNodeMap attrs=node.getAttributes();
- if(attrs.getLength()>0 && attrs!=null)
- {
- Node attr=attrs.getNamedItem(attrName);
- result=attr.getNodeValue();
- }
- }
- }
- }
- }
- return result;
- }
- publicstaticvoid main(String[] args)
- {
- String file="D://common//Tomcat60//smil.smil";
- XmlParser xml =new XmlParser(file);
- System.out.println(xml.getAttr("text","src"));
- }
- }
解決多個節點問題,,比如下面的xml檔案
- <smil xmlns="http://www.w3.org/2000/SMIL20/CR/Language">
- <head>
- <layout>
- <root-layout height="100%" width="100%" />
- <region id="Image" top="0" left="0" height="80%" width="100%"/>
- <region id="Text" top="80%" left="0" height="20%" width="100%"/>
- </layout>
- </head>
- <body>
- <par dur = "5000ms">
- <img region="Image" src="/contentlib/5/6/95/0.jpg"/>
- <audio src="/contentlib/5/6/95/0.wav"/>
- <text region="Text" src="/contentlib/5/6/95/0.txt"/>
- </par>
- <par dur = "5000ms">
- <img region="Image" src="/contentlib/5/6/95/1.gif"/>
- <audio src="/contentlib/5/6/95/1.wav"/>
- <text region="Text" src="/contentlib/5/6/95/1.txt"/>
- </par>
- <par dur = "5000ms">
- <img region="Image" src="/contentlib/5/6/95/2.gif"/>
- <audio src="/contentlib/5/6/95/2.wav"/>
- <text region="Text" src="/contentlib/5/6/95/2.txt"/>
- </par>
- </body>
- </smil>
要得出所有的src值,下面程式碼可以實現
- import java.io.InputStream;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.LinkedList;
- import java.util.List;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.ParserConfigurationException;
- import javax.xml.parsers.FactoryConfigurationError;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import org.w3c.dom.NamedNodeMap;
- import org.w3c.dom.NodeList;
- import org.w3c.dom.Node;
- import org.xml.sax.SAXException;
- /**
- * Description: xml解析類
- * @author wayfoon
- * @version
- */
- publicclass XmlParser
- {
- privatestatic DocumentBuilderFactory factory;
- privatestatic DocumentBuilder builder;
- private Document doc;
- private Element root;
- private String fileName;
- private InputStream inputstream;
- /**
- * 解析檔案xml
- * @param file
- * String
- */
- public XmlParser(String file)
- {
- if (file == null)
- {
- return;
- }
- this.fileName = file;
- try
- {
- load();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- return;
- }
- }
- /**
- * 解析輸入流xml
- *
- * @param input
- * InputStream
- */
- public XmlParser(InputStream input)
- {
- if (input == null)
- {
- return;
- }
- inputstream = input;
- try
- {
- loadStream();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- return;
- }
- }
- /**
- * 獲取XML檔案中指定標籤所對應的節點集合
- *
- * @param key
- * String 標籤名字
- * @return ArrayList 指定標籤對應的節點集
- */
- public ArrayList findNodes(String key)
- {
- NodeList nodes = root.getElementsByTagName(key);
- ArrayList nodeList = new ArrayList();
- for (int i = 0; i < nodes.getLength(); i++)
- {
- nodeList.add(i, (Node) nodes.item(i));
- }
- return nodeList;
- }
- /**
- * 初始化XML
- *
- * @throws IOException
- */
- publicvoid loadStream() throws IOException
- {
- try
- {
- loadXMLParser();
- doc = builder.parse(inputstream);
- root = doc.getDocumentElement();
- }
- catch (IOException ex)
- {
- ex.printStackTrace();
- }
- catch (SAXException ex)
- {
- ex.printStackTrace();
- }
- finally
- {
- inputstream.close();
- }
- }
- /**
- * 初始化XML
- *
- * @throws IOException
- */
- publicvoid load() throws IOException
- {
- try
- {
- loadXMLParser();
- doc = builder.parse(fileName);
- root = doc.getDocumentElement();
- }
- catch (SAXException SaxEx)
- {
- SaxEx.printStackTrace();
- thrownew IOException(SaxEx.getMessage() + "XML file parse error:"
- + SaxEx.getException());
- }
- catch (IOException IoEx)
- {
- IoEx.printStackTrace();
- thrownew IOException(IoEx.getMessage() + "XML file parse error:");
- }
- catch (Exception ex)
- {
- ex.printStackTrace();
- thrownew IOException(ex.getMessage() + "XML file parse error:");
- }
- }
- /**
- * 初始化XML
- *
- * @throws IOException
- */
- privatevoid loadXMLParser() throws IOException
- {
- if (builder == null)
- {
- try
- {
- factory = DocumentBuilderFactory.newInstance();
- builder = factory.newDocumentBuilder();
- }
- catch (ParserConfigurationException ex)
- {
- thrownew IOException("XML Parser load error:"
- + ex.getLocalizedMessage());
- }
- catch (FactoryConfigurationError ConfErrEx)
- {
- thrownew IOException("XML Parser load error:"
- + ConfErrEx.getLocalizedMessage());
- }
- catch (Exception Ex)
- {
- thrownew IOException("XML Parser load error:"
- + Ex.getLocalizedMessage());
- }
- }
- }
- /**
- * 獲取XML檔案中某級節點下一級元素的值
- *
- * @param node
- * 節點物件
- * @param subTagName
- * subTagName元素的標籤名
- * @return String 該標記元素的的內容
- */
- publicstatic String getSubTagValue(Node node, String subTagName)
- {
- String returnString = "";
- if ((node != null) && (subTagName != null))
- {
- NodeList children = node.getChildNodes();
- for (int innerLoop = 0; innerLoop < children.getLength(); innerLoop++)
- {
- Node child = children.item(innerLoop);
- if ((child != null) && (child.getNodeName() != null)
- && (child.getNodeName().equals(subTagName)))
- {
- Node grandChild = child.getFirstChild();
- if (grandChild != null)
- {
- return grandChild.getNodeValue();
- }
- }
- }
- }
- return returnString;
- }
- /**
- * 獲取XML檔案中某單一值
- *
- * @param node
- * 節點物件
- * @param subTagName
- * subTagName元素的標籤名
- * @return String 該標記元素的的內容
- */
- public String getresult(String name)
- {
- String result = "";
- ArrayList resultlist = findNodes(name);
- if ((resultlist != null) && (resultlist.size() > 0))
- {
- for (int i = 0; i < resultlist.size(); i++)
- {
- Node node = (Node) resultlist.get(i);
- if (node instanceof Element)
- {
- if ((node != null) && (node.getNodeName() != null)
- && (node.getNodeName().equals(name)))
- {
- Node grandChild = node.getFirstChild();
- if (grandChild != null)
- {
- result = grandChild.getNodeValue();
- }
- }
- }
- }
- }
- return result;
- }
- /**
- * 得到某一節點指定屬性的值
- * @param node
- * @param name
- * @param attrName
- * @return
- */
- public String getAttrByNode(Node node, String name, String attrName)
- {
- NodeList list = node.getChildNodes();
- // System.out.println("---"+list.getLength());
- String result = "";
- Node child = null;
- for (int innerLoop = 0; innerLoop < list.getLength(); innerLoop++)
- {
- child = list.item(innerLoop);
- if (child instanceof Element)
- {
- if ((child != null) && (child.getNodeName() != null)
- && (child.getNodeName().equals(name)))
- {
- // 遍歷整個xml某節點指定的屬性
- NamedNodeMap attrs = child.getAttributes();
- if (attrs.getLength() > 0 && attrs != null)
- {
- Node attr = attrs.getNamedItem(attrName);
- result = attr.getNodeValue();
- }
- }
- }
- }
- return result;
- }
- /**
- * 得到節點屬性值,節點可能存在多個,返回的是個陣列
- *
- * @param name
- * @param attrName
- * @return
- */
- public String[] getAttr(String name, String attrName)
- {
- int len = 0;
- String result[] = new String[] {};
- ArrayList resultlist = findNodes(name);
- if ((resultlist != null) && (resultlist.size() > 0))
- {
- result = new String[resultlist.size() * 3];
- for (int i = 0; i < resultlist.size(); i++)
- {
- Node node = (Node) resultlist.get(i);
- if (node instanceof Element)
- {
- if ((node != null) && (node.getNodeName() != null)
- && (node.getNodeName().equals(name)))
- {
- String img = getAttrByNode(node, "img", "src");
- String audio = getAttrByNode(node, "audio", "src");
- String text = getAttrByNode(node, "text", "src");
- if (!"".equals(img) && img != null)
- {
- result[len++] = img;
- }
- else
- {
- result[len++] = "";
- }
- if (!"".equals(audio) && audio != null)
- {
- result[len++] = audio;
- }
- else
- {
- result[len++] = "";
- }
- if (!"".equals(text) && text != null)
- {
- result[len++] = text;
- }
- else
- {
- result[len++] = "";
- }
- // System.out.println(result[len]);
- }
- }
- }
- }
- //System.out.println(result.length);
- return result;
- }
- publicstaticvoid main(String[] args)
- {
- String file = "D://**//smil.smil";
- XmlParser xml = new XmlParser(file);
- // XmlParser xml1 =new XmlParser(file1);
- String[] strings = xml.getAttr("par", "dur");
- for (int i = 0; i < strings.length; i++)
- {
- System.out.println(strings[i]);
- }
- }
- }
輸入結果:就是我們想得到的