`
qqdwll
  • 浏览: 131580 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

XML

    博客分类:
  • Java
阅读更多
XML 处理实践

一: DOM解析
1. 把XML文挡以String读出
File docFile = new File( fileName);
//FileUtils. commons-io-1.4.jar
String result = FileUtils.readFileToString(new File(fileName), UTF_8);

2. 把String写出到XML文挡
File dest = new File (fileName);
String contens = contents;
FileUtils.writeStringToFile(dest, contents, UTF_8);

3. String to org.w3c.dom.Document
//DocumentBuilderFactory. xml-apis.jar
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
String nodeData = xml content;
Document result = builder.parse(new InputSource(new StringReader(nodeData)));

4. String to org.apache.xerces.dom.DocumentImpl
     //DocumentImpl.  xercesImpl.jar
     DocumentImpl result = null;
     //DOMParser.  xercesImpl.jar
     DOMParser parser = new DOMParser();
     //xml-apis.jar
     DefaultHandler defaultHandler = new DefaultHandler();
     parser.setErrorHandler(defaultHandler);
     InputSource is = new InputSource(new StringReader(nodeData));
     parser.parse(is);
     result = (DocumentImpl) parser.getDocument();

5.  通过父节点, 返回一个 (所有)的子节点
    /**Given any parent element and the tag name of a child element, this returns
    the first child element. If there is multiple child elements, this method
    only retrieves the first. It will also create a child element if it does
    not exist and add it to the parent element if the <code>addChildIfNotPresent</code>
    flag is set to true.
    */

    public static Element findChildForParent(Element parentElement, String childTagName, boolean addChildIfNotPresent) {
        Element childElement = null;
        if (parentElement != null) {
            NodeList list = parentElement.getElementsByTagName(childTagName);
            if (list != null && list.getLength() > 0) {
                childElement = (Element)list.item(0);
            } else {
                if (addChildIfNotPresent) {
                    childElement = addElement(parentElement, childTagName);
                }
            }
        }
        return childElement;
    }

     public static Element addElement(Element parentElement, String childTagName, String value) {
        Element childElement = null;
        if (parentElement != null) {
            childElement = parentElement.getOwnerDocument().createElement(childTagName);
            parentElement.appendChild(childElement);
            if (value != null) {
                Node text = parentElement.getOwnerDocument().createTextNode(value);
                childElement.appendChild(text);
            }
        }
        return childElement;
    }

6。 取得text文本的一些方法

   a. //xmi-apis.jar
  /**
     *  Get the text of an Element
     *
     *@param  textElement  the Element to retrieve the text from
     *@return              the text of the Element
     */
    public static String textForElement(Element textElement) {
        String value = null;

        if (textElement != null) {
            Node child = textElement.getFirstChild();
            while (child != null) {
                if ((child.getNodeType() == Node.TEXT_NODE) || (child.getNodeType() == Node.CDATA_SECTION_NODE)) {
                    value = child.getNodeValue();
                    child = null;
                } else {
                    child = child.getNextSibling();
                }
            }
        }

        return value;
    }

    b. // CachedXPathAPI come from  xalan.jar
       //org.w3c.dom.Node implement in xml-apis.jar
      /**
     *  Description of the Method
     *
     *@param  xpathToElement      Description of the Parameter
     *@param  cachedXpath         Description of the Parameter
     *@param  node                Description of the Parameter
     *@return                     Description of the Return Value
     *@exception  CVXMLException  Description of the Exception
     */
    public static String textForElement(String xpathToElement, Node node, org.apache.xpath.CachedXPathAPI cachedXpath) throws CVXMLException {
        String results = null;
        if (cachedXpath != null) {
            try {
                if (logger.isDebugEnabled()) logger.debug("getting textForElement using cachedxpath and xpath : " + cachedXpath + " -- " + xpathToElement);
                Node n = cachedXpath.selectSingleNode(node, xpathToElement);
                if (n != null) {
                    results = textForElement((Element)n);
                }
            } catch (Throwable t) {
                if (logger.isDebugEnabled()) logger.debug("Error getting textForElement", t);
                //throw new CVXMLException(t);
            }
        } else {
            results = textForElement(xpathToElement, node);
        }

        return results;
    }
   
    c. Using xpath get the text from Document.
    //XPathAPI. xalan.jar
    /**
     *  Description of the Method
     *
     *@param  xpathToElement      Description of the Parameter
     *@param  doc                 Description of the Parameter
     *@return                     Description of the Return Value
     *@exception  CVXMLException  Description of the Exception
     */
    public static String textForElement(String xpathToElement, Document doc) throws CVXMLException {
        String results = null;
        try {
            if (logger.isDebugEnabled()) logger.debug("getting textForElement using old way -- no cachedxpathapi");
            Node n = XPathAPI.selectSingleNode(doc.getDocumentElement(), xpathExpression);
            if (n != null) {
                results = textForElement((Element)n);
            }
        } catch (CVXMLException e) {
            e.appendLogInfo("Unable to find a node using the xpath : " + xpathToElement);
            throw e;
        } catch (Throwable t) {
            if (logger.isDebugEnabled()) logger.debug("Error getting textForElement", t);
        }

        return results;
    }

7. 取得Attibute的方法
 //xml-apis.jar
  public static String textForAttribute(Element parentElement, String attributeName) {
        String attributeText = null;
        Attr classAttribute = parentElement.getAttributeNode(attributeName);
        if (classAttribute != null) {
            attributeText = classAttribute.getValue();
        }

        return attributeText;
    }

  8. 设置text和attribute的方法
     //xml-apis.jar
   public static void setTextForElement(Element textElement, String textToBeUsed) {
        if (textToBeUsed != null) {
            if (textToBeUsed.length() > 0){
                textToBeUsed = StringUtils.removeIncompatibilityCharacters(textToBeUsed);
            }
            if (textElement.hasChildNodes()) {
                // search for a text or cdata node to set the value of
                boolean found = false;
                boolean done = false;
                Node child = textElement.getFirstChild();
                while (!found && !done) {
                    if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
                        done = true;
                        found = true;
                    } else {
                        child = child.getNextSibling();
                        if (child == null) {
                            done = true;
                        }
                    }
                }

                if (found) {
                    child.setNodeValue(textToBeUsed);
                } else {

                    //Node text = textElement.getOwnerDocument().createTextNode(textToBeUsed);//GR 04/01/2004 -- Changed to create CData Section instead
                    Node text = textElement.getOwnerDocument().createCDATASection(textToBeUsed);
                    textElement.appendChild(text);
                }
            }

            else {
                // no text nodes found to set a value for, so must create one
                //textElement.appendChild(textElement.getOwnerDocument().createTextNode(textToBeUsed));//GR 04/01/2004 -- Changed to create CData Section instead
                textElement.appendChild(textElement.getOwnerDocument().createCDATASection(textToBeUsed));
            }
        }
    }

   public static String removeIncompatibilityCharacters(String textStr) {

        CharArrayWriter charArrayWriter = new CharArrayWriter();

        for (int i = 0; i < textStr.length(); i++) {
            if (Character.isDefined(textStr.charAt(i))) {

                int charVal = (int) textStr.charAt(i);
                // Control Characters --> NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS
                if (charVal >= 0x00 && charVal <= 0x08) {
                    continue;
                }
                // Control Characters --> CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US
                if (charVal >= 0x0B && charVal <= 0x1F) {
                    continue;
                }
                // The remaining characters are defined at http://www.w3.org/TR/2006/REC-xml-20060816/#charsets
                if (charVal >= 0x7F && charVal <= 0x84) {
                    continue;
                }
                if (charVal >= 0x86 && charVal <= 0x9F) {
                    continue;
                }
                if (charVal >= 0xFDD0 && charVal <= 0xFDDF) {
                    continue;
                }
                if (charVal >= 0x1FFFE && charVal <= 0x1FFFF) {
                    continue;
                }
                if (charVal >= 0x2FFFE && charVal <= 0x2FFFF) {
                    continue;
                }
                if (charVal >= 0x3FFFE && charVal <= 0x3FFFF) {
                    continue;
                }
                if (charVal >= 0x4FFFE && charVal <= 0x4FFFF) {
                    continue;
                }
                if (charVal >= 0x5FFFE && charVal <= 0x5FFFF) {
                    continue;
                }
                if (charVal >= 0x6FFFE && charVal <= 0x6FFFF) {
                    continue;
                }
                if (charVal >= 0x7FFFE && charVal <= 0x7FFFF) {
                    continue;
                }
                if (charVal >= 0x8FFFE && charVal <= 0x8FFFF) {
                    continue;
                }
                if (charVal >= 0x9FFFE && charVal <= 0x9FFFF) {
                    continue;
                }
                if (charVal >= 0xAFFFE && charVal <= 0xAFFFF) {
                    continue;
                }
                if (charVal >= 0xBFFFE && charVal <= 0xBFFFF) {
                    continue;
                }
                if (charVal >= 0xCFFFE && charVal <= 0xCFFFF) {
                    continue;
                }
                if (charVal >= 0xDFFFE && charVal <= 0xDFFFF) {
                    continue;
                }
                if (charVal >= 0xEFFFE && charVal <= 0xEFFFF) {
                    continue;
                }
                if (charVal >= 0xFFFFE && charVal <= 0xFFFFF) {
                    continue;
                }
                if (charVal >= 0x10FFFE && charVal <= 0x10FFFF) {
                    continue;
                }

                charArrayWriter.write(charVal);
            }
        }

        return new String(charArrayWriter.toCharArray());
    }

     public static void setTextForAttribute(Element parentElement, String attributeName, String attributeValue) {
        parentElement.setAttribute(attributeName, attributeValue);
    }


9. 创建Document
   a. //xml-apis.jar
   //Creates a new document object with the root node having the name: <code>rootElementName</code>\
    public static Document createDocumentWithRoot(String rootElementName, boolean x) {
        Document newRecordDoc = null;
        if (rootElementName != null && !rootElementName.trim().equals("")) {
            newRecordDoc = createDocument(true);
            // Once the new document has been created, add the necessary root element
            newRecordDoc.appendChild(newRecordDoc.createElement(rootElementName));
        }
        return newRecordDoc;
    }


    b. //Creates a new document object without the root node being set on the
   public static Document createDocument(boolean x) {
        Document newRecordDoc = null;
        try {
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            newRecordDoc = docBuilder.newDocument();
        } catch (Exception e) {
            ExceptionLogWriter.logException(e, "DOMHelper.createDocument(). Problem instantiating a new DocumentBuilder");
        }
        return newRecordDoc;
    }
   
10. 替换节点
  a. //xml-apis.jar
     public static Document replaceRootNodeName(String xml, String newValue) throws CVXMLException {
        Document doc = stringToDocument(xml, true);
        replaceRootNodeName(doc, newValue);
        return doc;
    }
   
    b.
     public static void replaceRootNodeName(Document doc, String newValue) {
        replaceNodeName(doc, doc.getDocumentElement(), newValue);
    }
   
    c.
     public static void replaceNodeName(Document doc, Element element, String newValue) {
       //Create an element with the new name
        Element element = doc.createElement(newValue);
       
       // Copy the attributes to the new element
        NamedNodeMap attrs = element.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Attr attr2 = (Attr)doc.importNode(attrs.item(i), true);
            element2.getAttributes().setNamedItem(attr2);
        }
       
        // Move all the children
        while (element.hasChildNodes()) {
            element2.appendChild(element.getFirstChild());
        }
       
         // Replace the old node with the new node
        element.getParentNode().replaceChild(element2, element);

     }
    
    
二. SAX 解析
   class XMLDocument extends DefaultHandler {
        Document doc;
        String elementName = "";
        String attribName = "";
        String attribVal = "";
        boolean addAttr = false;
        Element currElement;
        Element root;
        String rootName;
        boolean hasDocument = false;
        boolean hasRoot = false;
        int count = 0;

        /**  Constructor for the XMLDocument object */
        XMLDocument() {
            super();
            hasDocument = false;
        }

        /**
         *@param  val  Document
         */
        XMLDocument(Document val) {
            super();
            doc = val;
            hasDocument = true;
        }

        /**
         *  Method to set the Root
         *
         *@param  val  The new root value
         */
        public void setRoot(String val) {
            rootName = val;
            hasRoot = true;
        }

        /**
         *  Method to add an attribute.
         *
         *@param  element    String containing the elementName
         *@param  attribute  String containing the attribute name
         *@param  value      String containing the attribute value
         */
        public void addAttribute(String element, String attribute, String value) {
            elementName = element;
            attribName = attribute;
            attribVal = value;
            addAttr = true;
        }

        /**
         *@exception  SAXException  If the root element name is missing
         */
        public void startDocument() throws SAXException {
            if (!hasDocument) {
                try {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder parser = factory.newDocumentBuilder();
                    doc = parser.newDocument();
                } catch (Exception e) {
                    throw new SAXException(e);
                }

                if (rootName == null || rootName.equals("")) {
                    throw new SAXException("Missing root element name, call setRoot() first");
                }
            }
            if (hasRoot) {
                root = (Element)doc.createElement(rootName);
                doc.appendChild(root);
            }

        }

        /**
         *@param  uri               String containing the uri
         *@param  localName         String containing the localName
         *@param  rawName           String containing the rawName
         *@param  atts              Attributes
         *@exception  SAXException  Description of the Exception
         */
        public void startElement(String uri, String localName, String rawName, Attributes atts) throws SAXException {
            // Assume the first element encountered is the root element

            // Check the element to see if it is one we are interested in processing
            if (hasRoot) {
                if (!rawName.equalsIgnoreCase(rootName)) {
                    currElement = (Element)doc.createElement(rawName);
                    for (int i = 0; i < atts.getLength(); i++) {
                        currElement.setAttribute(atts.getQName(i), atts.getValue(i));
                    }
                    if (rawName.equals(elementName) && addAttr) {
                        // Add the new attribute if specified
                        currElement.setAttribute(attribName, attribVal);
                    }
                    root.appendChild(currElement);
                } else {
                    currElement = (Element)doc.createElement(rawName);
                    for (int i = 0; i < atts.getLength(); i++) {
                        currElement.setAttribute(atts.getQName(i), atts.getValue(i));
                    }

                }
            } else {
                // Create a new element - used for stringToDoc(String) method
                if (count == 0) {
                    root = (Element)doc.createElement(rawName);
                    doc.appendChild(root);
                }
                currElement = (Element)doc.createElement(rawName);
                for (int i = 0; i < atts.getLength(); i++) {
                    currElement.setAttribute(atts.getQName(i), atts.getValue(i));
                }
                root.appendChild(currElement);
                count++;
            }
        }

        /**
         *@param  ch                Description of the Parameter
         *@param  start             Description of the Parameter
         *@param  length            Description of the Parameter
         *@exception  SAXException  Description of the Exception
         */
        public void characters(char[] ch, int start, int length) throws SAXException {
            Text text = doc.createTextNode(new String(ch, start, length));
            if (currElement != null) {
                currElement.appendChild(text);
            }
        }

        /**
         *  Description of the Method
         *
         *@return    Description of the Return Value
         */
        public Document document() {
            return doc;
        }

    }
   
    //xml-apis.jar
    public Object process( InputSource is ) {
           protected List tags = new ArrayList(0);
           SAXParserFactory spf = SAXParserFactory.newInstance();
           spf.setValidating( strict );
           SAXParser sp = spf.newSAXParser();
           XMLReader xmlReader = sp.getXMLReader();
           xmlReader.setContentHandler( this );
           xmlReader.setErrorHandler( this );
           if( entityResolver != null ) {
               xmlReader.setEntityResolver( entityResolver );
           }
           xmlReader.parse( is );
           if( tags.size() == 0 ) return finish( null );
           return finish( tags.remove(0) );

    }
   
    MyProcess processor = new ProcessImpl(conf, rc);
    //XMLBuilder extends XMLDocument 策略模式
    XMLBuilder xb = new XMLBuilder(processor);
    xb.process(new StringReader( ""));
   
    三. xsl parse xml
    //xml-apis.jar
    protected void transformXml(String path, String documentXml) {
StreamSource xsl = new StreamSource(new File(xslFileName));
StringReader reader = new StringReader(documentXml);
StreamSource xml = new StreamSource(reader);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);

Transformer transformer = null;
try {
transformer = TransformerFactory.newInstance().newTransformer(xsl);
}

try {
if(null != transformer) {
transformer.transform(xml, result);
}
}


      xsl:
        <root>
        <xsl:template match="/book">
        <xsl:if test="date/text()" >
          <newnode><xsl:value-of select="date"/></facet>
        </xsl:if>
        <xsl:apply-templates select="Auther/lan"/>
        </root>


    <xsl:template match="Auther/lan">
     <xsl:if test="position()=1">
        <p><xsl:value-of select="key"/></p>
    </xsl:if>
   </xsl:template>
分享到:
评论

相关推荐

    xml2axml反编译AndroidManafest文件

    使用java工具xml2axml.jar反编译AndroidManafest文件 通过xml2axml.jar工具反编译AndroidManafest文件 还原AndroidManafest.xml详细过程: 1、获取到apk 2、解压获取里面的AndroidManifest.xml文件 3、在xml2axml....

    maven的本地仓库配置文件settings.xml和项目中文件pom.xml.zip

    一、Idea关联的maven本地仓库配置文件settings.xml (1)必须使用默认文件名 D:\developsoft\javaweb\commonPlugins\maven\apache-maven-3.8.1_first\conf\settings.xml 二、Myeclipse关联的maven本地仓库配置文件...

    xml加密解密工具XMLEncryption

    xml加密(XML Encryption)是w3c加密xml的标准。这个加密过程包括加密xml文档的元素及其子元素,通过加密,xml的初始内容将被替换,但其xml格式仍然被完好的保留。 介绍 我们有3个加密xml的方法 1、仅仅使用对称...

    Tinyxml 源代码(VC6 & VS2005)

    TinyXML是一个简单小巧,可以很容易集成到其它程序中的C++ XML解析器。 它能做些什么 简单地说,TinyXML解析一个XML文档并由此生成一个可读可修改可保存的文档对象模型(DOM)。 XML的意思是“可扩展标记语言...

    XML与XMLSchema

    XML发展历史概述 XML文档组成元素 XML Schema组成元素 XML相关API

    Android APK xml 批量解密工具

    android开发中有时会想研究借鉴一下设计思路和UI风格,但解压apk包后 layout文件夹下xml文件一般都是加密的。在网上找到了一个工具,可以完美地解密xml文件,但这个工具的使用方法是:调cmd 然后...

    vb6XML读写

    vb中读写XML文件实例Dim XMLDoc As DOMDocument Dim root As IXMLDOMNode Dim xlst As IXMLDOMNodeList, xlst1 As IXMLDOMNodeList Dim xn As IXMLDOMNode Dim xnf As IXMLDOMNode Dim xe As IXMLDOMElement Set ...

    QT中读取XML文件三种方式 的实例

    XML(eXtensible Markup Language)是一种通用的文本格式,被广泛运用于数据交换和数据存储(虽然近年来 JSON 盛行,大有取代 XML 的趋势,但是对于一些已有系统和架构,比如 WebService,由于历史原因,仍旧会继续...

    纯C语言解析xml字符串

    纯C语言解析xml字符串,有实例,保证可用,含makefile xmlparse.c xmlparse.h testxml.c 目录:/export/home/chcard/testxml 日志:/export/home/chcard/log testxml.c 是一个测试用例,包含了常用的方法,并有注解 ...

    Altova XMLSpy2013简体中文版破解补丁

    Altova XMLSpy是一款业界最畅销的XML编辑器,这款XMLSpy2013重点新增了智能修复、Java应用程序无缝集成、集成外部程序等新功能,而且本站提供的是中文破解版,能给用户带来极大的方便。 Altova XMLSpy主要用于建模,...

    xml和java bean互相转换工具包(简单易用)

    xml 与 bean 互相转换 工具类 1、bean类的属性需要遵守BEAN规范,否则 无法 读存BEAN值。 2、bean类的属性如果 是集合 只支持数组以及List、Map、Set。 3、bean类属性(boolean除外)前面两个字母要么全部小写,要么...

    andxml xml解密工具

    andxml汉化版是一个xml文件反编译工具,可与APKTOOL反编译配合使用,APK文件使用APKTool反编译生成XML文件后,就可以直接通过它进行汉化编辑 注意: 1、一键机器翻译会造成某些代码出现翻译错误现象,请人工识别。...

    opencv+python 人脸识别的xml文件

    haarcascade_eye.xml haarcascade_eye_tree_eyeglasses.xml haarcascade_frontalcatface.xml haarcascade_frontalcatface_extended.xml haarcascade_frontalface_alt.xml haarcascade_frontalface_alt_tree.xml haar...

    XML - 实验(2) -- Schema

    《XML》实验任务书 【2】 XML Schema [实验目的] 1、学习如何使用XMLSPY集成开发环境完成XML Schema相关的开发工作。 2、掌握XML Schema与DTD之间的区别,能够完成两者之间的转换;掌握在XML Schema中如何定义元素...

    让开源项目TinyXml支持Unicode(wchar_t)

    开源项目TinyXml项目所涉及的字符编码说明如下: 1. TinyXml函数调用接口的字符型参数,仅支持`窄字符`格式(char*),不兼容`宽字符`格式(wchar_t*)。 2. TinyXml函数提供的Xml内容解析功能,仅支持以ANSI编码和UTF...

    java在线解析xmljava在线解析xmljava在线解析xmljava在线解析xml

    java在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava在线解析xmljava...

    易语言 xml解析 易语言 xml解析 教程 带源码

    易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 易语言 xml解析 教程 带源码

    tinyxml与tinyxml2

    tinyxml与tinyxml2两个版本的源码,操作xml很方便,解压可以直接使用.

    动态生成Rss文件 Xml操作 Xml文件的修改

    动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件 Xml操作 Xml文件的修改动态生成Rss文件...

    Maven pom.xml与settings.xml详解

    主要介绍了Maven pom.xml与settings.xml详解的相关资料,这里对pom.xml与setting.xml详细的研究说明,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics