// package ...; import java.io.*; import java.net.*; import java.util.*; import org.w3c.dom.Text; import org.w3c.dom.CDATASection; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.OutputKeys; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.DOMException; /** Command Line: java -Djavax.xml.parsers.SAXParserFactory=MyParserFactory MyClass In Code: System.setProperty("javax.xml.parsers.SAXParserFactory", "foo.bar.MyParserFactory"); System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "foo.bar.MyDocumentBuilder"); */ public class XmlCtl { private Document doc; private String dtd; private String newDTD = ""; public Document getDocument() throws Exception { return doc; } /* Salto de proxy http://www.developer.com/java/other/article.php/1551421 */ public Document getDocument(String url) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // factory.setValidating(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); doc = builder.parse(url); return (doc); } catch (Exception e) { throw new RuntimeException("Problemas en XmlCtl.getDocument"); } } /** * Ojo!: no comprobada */ public Document getDocument(String url, String otraDTD) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream in = new URL(url).openStream(); doc = builder.parse(in, otraDTD); return (doc); } catch (Exception e) { throw new RuntimeException("Problemas en XmlCtl.getDocument"); } } public void visualizarDOM() { NodeList nl = doc.getElementsByTagName("*"); System.out.println("\nTodos los niveles:"); for (int i = 0; i < nl.getLength(); i++) { Node nod = nl.item(i); try{ System.out.println(nod.getNodeName() + ": " + nod.getFirstChild().getNodeValue()); } catch(Exception e){ System.out.println(nod.getNodeName() + ": "); } } } public String getXML() throws Exception { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(doc); ByteArrayOutputStream ba = new ByteArrayOutputStream(); StreamResult result = new StreamResult(ba); transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result); return new String(ba.toByteArray()); } public void setNewDTD(String valor) { newDTD = valor; } public String getValorElement(Element elem) { return (elem.getFirstChild() == null) ? "" : elem.getFirstChild().getNodeValue(); } public String getPrimerValorTag(Element raiz, String tag) { if (raiz == null) return ""; NodeList nl = raiz.getElementsByTagName(tag); if (nl == null) return ""; Node nod = nl.item(0); if (nod == null) return ""; return (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); } public Element getPrimerElement(String tag, String valor) { return getPrimerElement(getElementRaiz(), tag, valor); } public Element getPrimerElement(Element raiz, String tag, String valor) { NodeList nl = raiz.getElementsByTagName(tag); int n = nl.getLength(); for (int i = 0; i < n; i++) { Node nod = nl.item(i); String nodTag = nod.getNodeName(); String nodValor = (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); if (nvl(tag).equals(nvl(nodTag)) && nvl(valor).equals(nvl(nodValor))) { return (Element) nod.getParentNode(); } } return null; } public Element[] getElements(Element raiz, String tag, String valor) { NodeList nl = raiz.getElementsByTagName(tag); int n = nl.getLength(); Vector v = new Vector(); for (int i = 0; i < n; i++) { Node nod = nl.item(i); String nodTag = nod.getNodeName(); String nodValor = (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); if (nvl(tag).equals(nvl(nodTag)) && nvl(valor).equals(nvl(nodValor))) { v.addElement(nod.getParentNode()); } } n = v.size(); Element[] aElems = new Element[n]; for (int i = 0; i < n; i++) { aElems[i] = (Element) v.elementAt(i); } return aElems; } public String getPrimerValorTag(String tag) { NodeList nl = doc.getElementsByTagName(tag); Node nod = nl.item(0); return (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); } public String getPrimerValorTag(String tag, String valor, String tag2) { Element elem = getPrimerElement(tag, valor); return getPrimerValorTag(elem, tag2); } public Element getPrimerElement(Element raiz, String tag) { if (raiz == null) return null; NodeList nl = raiz.getElementsByTagName(tag); if (nl == null) return null; Node nod = nl.item(0); if (nod == null) return null; return (Element) nod; } public Element getPrimerElement(String tag) { NodeList nl = doc.getElementsByTagName(tag); if (nl == null) return null; Node nod = nl.item(0); if (nod == null) return null; return (Element) nod; } public Element[] getElements(Element raiz, String tag) { NodeList nl = raiz.getElementsByTagName(tag); int n = nl.getLength(); Element[] aElems = new Element[n]; for (int i = 0; i < n; i++) aElems[i] = (Element) nl.item(i); return aElems; } public Element getElementRaiz() { return doc.getDocumentElement(); } public Element[] getElements() { return getElements("*"); } public Element[] getElements(String tag) { NodeList nl = doc.getElementsByTagName(tag); int n = nl.getLength(); Element[] aElems = new Element[n]; for (int i = 0; i < n; i++) aElems[i] = (Element) nl.item(i); return aElems; } public Element[] getElementsHijos() { return getElementsHijos(getElementRaiz()); } /** * Sólo primer nivel */ public Element[] getElementsHijos(Element raiz) { NodeList nl = raiz.getElementsByTagName("*"); int n = nl.getLength(); Vector v = new Vector(); for (int i = 0; i < n; i++) { Node padre = nl.item(i).getParentNode(); Node nodoRaiz = (Node) raiz; if (padre.equals(raiz)) v.addElement(nl.item(i)); } n = v.size(); Element[] aElems = new Element[n]; for (int i = 0; i < n; i++) { aElems[i] = (Element) v.elementAt(i); } return aElems; } public String getEtiqueta(Element elem) { return elem.getNodeName(); } public void agregarAtributo(Element nod, String nombreAtributo, String valorAtributo) { nod.setAttribute(nombreAtributo, valorAtributo); } public String getAtributo(Element nod, String nombreAtributo) { return nod.getAttribute(nombreAtributo); } public String[] getValoresTag(Element raiz, String tag) { NodeList nl = raiz.getElementsByTagName(tag); int n = nl.getLength(); String[] valores = new String[n]; for (int i = 0; i < n; i++) { Node nod = nl.item(i); valores[i] = (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); } return valores; } public String[] getValoresTag(String tag) { NodeList nl = doc.getElementsByTagName(tag); int n = nl.getLength(); String[] valores = new String[n]; for (int i = 0; i < n; i++) { Node nod = nl.item(i); valores[i] = (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); } return valores; } /** * Si tiene que valer para cualquier tag padre aceptar * */ public String getValorTagPorHermano(String tag, String tagPadre, String tagHermano, String valorTagHermano) { String valueTag = ""; NodeList nl = doc.getElementsByTagName(tagHermano); int n = nl.getLength(); for (int i = 0; i < n; i++) { Node nod = nl.item(i); String value = nod.getFirstChild().getNodeValue(); if (value.equals(valorTagHermano)) { Node np = nod.getParentNode(); if (np.getNodeName().equals(tagPadre)) { for(Node child = nod.getNextSibling();child != null; child = child.getNextSibling()) { if (child.getNodeName().equals(tag)) valueTag = (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); } } } } return valueTag; } public String getValorTagPorHermano(String tag, String tagHermano, String valorTagHermano) { String valueTag = ""; NodeList nl = doc.getElementsByTagName(tagHermano); int n = nl.getLength(); for (int i = 0; i < n; i++) { Node nod = nl.item(i); String value = nod.getFirstChild().getNodeValue(); if (value.equals(valorTagHermano)) { for(Node child = nod.getNextSibling();child != null; child = child.getNextSibling()) { if (child.getNodeName().equals(tag)) valueTag = (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); } } } return valueTag; } public String[] getValorTagPorHermano(String tag, String tagHermano) { NodeList nl = doc.getElementsByTagName(tagHermano); int n = nl.getLength(); int j = 0; String[] valueTag = new String[n]; for (int i = 0; i < n; i++) { Node nod = nl.item(i); String value = nod.getFirstChild().getNodeValue(); for(Node child = nod.getNextSibling();child != null; child = child.getNextSibling()) { if (child.getNodeName().equals(tag)) { valueTag[j] = (nod.getFirstChild() == null) ? "" : nod.getFirstChild().getNodeValue(); j++; } } } int i = 0; for (int ii = 0; valueTag[ii]!=null ; ii++) { i = ii; } String[] valores = new String[i+1]; for (int jj = 0; jj<=i ; jj++) { valores[jj] = valueTag[jj]; } return valores; } public void agregarTag(String tagPadre, String nombreTag, String valorTag) throws ParserConfigurationException { agregarTag(tagPadre, nombreTag, valorTag, false, true); } public void agregarTag(String tagPadre, String nombreTag, String valorTag, boolean isCDATA) throws ParserConfigurationException { agregarTag(tagPadre, nombreTag, valorTag, isCDATA, true); } public void agregarTag(String tagPadre, String nombreTag, String valorTag, boolean isCDATA, boolean hijoTexto) throws ParserConfigurationException { Text text; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document newDoc = builder.newDocument(); Element tag = (Element) newDoc.createElement (nombreTag); if (isCDATA) text = newDoc.createCDATASection(valorTag); else text = newDoc.createTextNode(valorTag); if (hijoTexto) tag.appendChild(text); newDoc.appendChild(tag); NodeList nl = doc.getElementsByTagName(tagPadre); int n = nl.getLength(); Node nodePadre = nl.item(n-1); Node node = doc.importNode(newDoc.getDocumentElement().cloneNode(true), true); nodePadre.appendChild(node); // for (int i = 0; i < n; i++) // { // Node nodePadre = nl.item(i); // Node node = doc.importNode(newDoc.getDocumentElement().cloneNode(true), true); // nodePadre.appendChild(node); // } } public void clonarTag(String nombreTag, String tagDestino, boolean hijos) { NodeList nl = doc.getElementsByTagName(nombreTag); Node node = nl.item(0); NodeList nl2 = doc.getElementsByTagName(tagDestino); int n = nl2.getLength(); for (int i = 0; i < n; i++) { Node nodePadre = nl2.item(i); nodePadre.appendChild(node.cloneNode(hijos)); } } public void borrarTag(String tagPadre, String tag) { NodeList nl = doc.getElementsByTagName(tagPadre); int n = nl.getLength(); for (int i = 0; i < n; i++) { Node nod = nl.item(i); NodeList nl2 = nod.getChildNodes(); for (int j = 0; j < nl2.getLength(); j++) { Node nodHijo = nl2.item(j); if (nodHijo.getNodeName().equals(tag)) { nod.removeChild(nodHijo); } } } } public void borrarTextTag(String tagPadre, String tag) { NodeList nl = doc.getElementsByTagName(tagPadre); int n = nl.getLength(); for (int i = 0; i < n; i++) { Node nod = nl.item(i); NodeList nl2 = nod.getChildNodes(); for (int j = 0; j < nl2.getLength(); j++) { Node nodHijo = nl2.item(j); if (nodHijo.getNodeName().equals(tag)) { if (nodHijo.getFirstChild()!=null) nodHijo.removeChild(nodHijo.getFirstChild()); } } } } /** * Sirve para borrar la referencia a la DTD de un XML */ public void generaFicheroOtraDTD(String ficheroSalida, String otraDTD) { try { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1"); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, otraDTD); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); File newXML = new File(ficheroSalida); FileOutputStream os = new FileOutputStream(newXML); StreamResult result = new StreamResult(os); transformer.transform(source, result); os.close(); } catch (Exception e) { throw new RuntimeException("Problemas en XmlCtl.generaFicheroOtraDTD"); } } public void setDTD(String url) { dtd = url; } public String fixBarra(String cadOrig) { StringBuffer cadDesti = new StringBuffer(255); for (int i = 0; i < cadOrig.length(); i++) { if (cadOrig.charAt(i) == '\\') { cadDesti.append('/'); } else { cadDesti.append(cadOrig.charAt(i)); } } return cadDesti.toString(); } public String nvl(String s) { return s == null ? "" : s.trim(); } public void moverElement(Element elem, int posDestino) { NodeList nl = doc.getElementsByTagName(elem.getParentNode().getNodeName()); int n = nl.getLength(); Node nod = nl.item(0); Node nodeClon = elem.cloneNode(true); doc.removeChild((Node)elem); NodeList nl2 = doc.getElementsByTagName(nod.getNodeName()); Node nod2 = nl2.item(posDestino); doc.insertBefore(nodeClon,nod2); } public void cambiarValorElement(Element elem, String valor, boolean isCDATA) { Text text = null; if (isCDATA) text = doc.createCDATASection(valor); else text = doc.createTextNode(valor); if (elem.getFirstChild()!=null) elem.removeChild(elem.getFirstChild()); elem.appendChild(text); } public static void main(String[] args) throws Exception { // En local: "file:///C:/Windows/Escritorio/pedido.xml"; XmlCtl xc = new XmlCtl(); xc.getDocument("http://www.bit-net.org/java/pedido.xml"); // xc.getDocument("C:\Archivos de programa\Apache Tomcat 4.0\webapps\teleaula\buzoncontenidos\actividad\244.xml"); // xc.getDocument("file:///C:/WINNT/Profiles/Administrador/Escritorio/Internetio.xml"); // xc.getDocument("file:///C:/Windows/Escritorio/237.xml"); String tag = "clienteId"; String valor = xc.getPrimerValorTag(tag); System.out.println("Valor de " + tag + " = |" + valor + "|"); System.out.println("-------------------------------------------------"); tag = "item"; String[] valores = xc.getValoresTag(tag); int n = valores.length; for (int i = 0; i < n; i++) { System.out.println("Valor de " + tag + "[" + i + "] = |" + valores[i] + "|"); } xc.agregarTag("clienteId", "tag-nuevo", "prueba"); System.out.println(xc.getXML()); } } /* Etiqueta Interna 0123A 02/06/2002 100 300 200 200 500 */