Home | History | Annotate | Download | only in support
      1 /*
      2  * Copyright (C) 2009 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package tests.support;
     18 
     19 import java.io.ByteArrayInputStream;
     20 import javax.xml.parsers.DocumentBuilder;
     21 import javax.xml.parsers.DocumentBuilderFactory;
     22 import org.w3c.dom.Document;
     23 import org.w3c.dom.Element;
     24 import org.w3c.dom.Node;
     25 import org.w3c.dom.NodeList;
     26 import static junit.framework.Assert.assertEquals;
     27 
     28 public class Support_Xml {
     29     public static Document domOf(String xml) throws Exception {
     30         // DocumentBuilderTest assumes we're using DocumentBuilder to do this parsing!
     31         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     32         dbf.setCoalescing(true);
     33         dbf.setExpandEntityReferences(true);
     34 
     35         ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
     36         DocumentBuilder builder = dbf.newDocumentBuilder();
     37 
     38         return builder.parse(stream);
     39     }
     40 
     41     public static String firstChildTextOf(Document doc) throws Exception {
     42         NodeList children = doc.getFirstChild().getChildNodes();
     43         assertEquals(1, children.getLength());
     44         return children.item(0).getNodeValue();
     45     }
     46 
     47     public static Element firstElementOf(Document doc) throws Exception {
     48         return (Element) doc.getFirstChild();
     49     }
     50 
     51     public static String attrOf(Element e) throws Exception {
     52         return e.getAttribute("attr");
     53     }
     54 }
     55