Java DOM:Evaluate方法中的错误;在特定位置添加元素

时间:2012-07-21 23:30:24

标签: java xml dom xml-parsing

我正在尝试在XHTML文件的特定位置(在id =“123”的div标签之后)使用DOM添加元素(javascript),我正在使用getElementById()。因此,为了定位元素的位置,我使用了两种方法。 1:不使用XPath(我在代码中注释了) 2:使用XPath(在论坛中提出建议后) 从第一种方法我可以得到相应类的值,其中id =“123”但它也抛出NullPointer异常。所以我使用了XPath,但在使用evaluate(String,Object)方法时显示错误。任何人都可以告诉我,我需要通过'sxp'传递什么参数 - > NodeList nodes = xPath.evaluate(sxp); 谢谢你!

我的XHTML:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-type" content="text/html;  charset=utf-8" />
<script></script>
</head>
<body>
<div id="outer">
<div id="main">
<div id="nD">
<p id="nT">XSD</p>
</div>

<div class="TF" id="123">
<!--HERE I NEED TO INCLUDE ONE JAVASCRIPT-->

<div class="iDevice">
<img/>
<span>XYZ</span><br/>
<div>
<div>
</div>

<div class="q">
<br/><br/>
<div>1<span> ABC</span> 
</div>
<br/>T <input/> F <input/>
<div></div>
</div></div></div>
</div></div></div>
</body></html>

Java代码:

 public class Dom {
        protected static final String XML_FILE_NAME = "C:\\tmp\\part_1.html";
        protected static final String XML_FILE_NAME_COPY = "C:\\tmp\\part_1_copy.html";

        public static void main(String args[]) throws XPathExpressionException {
       try {
        File file = new File(XML_FILE_NAME);

        //Create instance of DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        factory.setNamespaceAware(true);
        //Get the DocumentBuilder
        DocumentBuilder docBuilder = factory.newDocumentBuilder();

        //Using existing XML Document
        Document doc = docBuilder.parse(file);

        // Get the head element by tag name directly
            Node head = doc.getElementsByTagName("head").item(0);

            //WITHOUT XPATH

        /*    NodeList nodelist=doc.getElementsByTagNameNS("http://www.w3.org/1999/xhtml","div");  
            for (int i=0; i<nodelist.getLength(); i++) {  
                Element elem=(Element)nodelist.item(i);  
                if (elem.getAttributeNode("id").getValue().equals("123")) {
                    //Printing the value for testing
                    System.out.println(elem.getAttributeNode("class").getValue());  
                }  
            } */

            //WITH XPATH
            String sxp="/x:html/x:body/x:div/x:div/x:div[@id = '123']";  
            XPath xPath = XPathFactory.newInstance().newXPath();  
            xPath.setNamespaceContext(new NamespaceContext() {  
                  public String getNamespaceURI(String prefix) {      
                      if (prefix.equals("x")) {  
                          return "http://www.w3.org/1999/xhtml";  
                      }  
                      return XMLConstants.NULL_NS_URI;  
                  }  

                  public String getPrefix(String namespaceURI) {  
                      if (namespaceURI.equals("http://www.w3.org/1999/xhtml")) {  
                          return "xhtml";  
                      }  
                      return null;  
                  }  

                  public Iterator <String> getPrefixes(String namespaceURI) {  
                      return null;  
                  }
            });
    //Before editing 
      //       NodeList nodes = xPath.evaluate(sxp); 
//After Editing but now I get the exception at this line
             NodeList nodes=(NodeList)xPath.evaluate(sxp,doc,XPathConstants.NODESET); 

            for (int i=0; i<nodes.getLength(); i++) {  
                Element elem=(Element)nodes.item(i);  
                //each one is the searched div element with id attribute 123 
                elem.setIdAttribute("id", true);
                Element found = doc.getElementById("123");

                Element script2 = doc.createElement("script");
                script2.setAttribute("src", "cal.js");
                script2.setAttribute("type","text/javascript");
                script2.setAttribute("xml:space","preserve");
                found.appendChild(script2);
          } 

        //set up a transformer
        ....
        .....
      } 
    }

我得到的错误 -

  

线程“main”中的异常javax.xml.transform.TransformerException:   错误引用的字面...预期的单引号!在   com.sun.org.apache.xpath.internal.compiler.XPathParser.error(未知   来源)at   com.sun.org.apache.xpath.internal.compiler.Lexer.tokenize(未知   来源)at   com.sun.org.apache.xpath.internal.compiler.Lexer.tokenize(未知   来源)at   com.sun.org.apache.xpath.internal.compiler.XPathParser.initXPath(未知   来源)com.sun.org.apache.xpath.internal.XPath。(未知   来源)com.sun.org.apache.xpath.internal.XPath。(未知   来源)at   com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(未知来源)     在com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(未知   来源)org.dom.Dom.main(Dom.java:78)   ---------------链接到------------------ javax.xml.xpath.XPathExpressionException at   com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(未知   来源)org.dom.Dom.main(Dom.java:78)引起:   javax.xml.transform.TransformerException:错误引用的文字...   预计单引号!在   com.sun.org.apache.xpath.internal.compiler.XPathParser.error(未知   来源)at   com.sun.org.apache.xpath.internal.compiler.Lexer.tokenize(未知   来源)at   com.sun.org.apache.xpath.internal.compiler.Lexer.tokenize(未知   来源)at   com.sun.org.apache.xpath.internal.compiler.XPathParser.initXPath(未知   来源)com.sun.org.apache.xpath.internal.XPath。(未知   来源)com.sun.org.apache.xpath.internal.XPath。(未知   来源)at   com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(未知来源)     ......还有2个

0 个答案:

没有答案