Skip to content

Instantly share code, notes, and snippets.

@ripper2hl
Created January 26, 2016 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ripper2hl/0b4f1e3ccfc339a40604 to your computer and use it in GitHub Desktop.
Save ripper2hl/0b4f1e3ccfc339a40604 to your computer and use it in GitHub Desktop.
Manipulacion de XML en formato String con JDOM2
import java.io.IOException;
import java.io.StringReader;
import java.util.Calendar;
import java.util.Date;
import org.apache.log4j.Logger;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class UtilXml {
/**
* Obtiene el valor de un atributo de xml
* @param xml xml
* @param atributo Atributo a buscar de la orden de venta
* @return valor del atributo en el xml
* @author Jesus Perales.
*/
public static String obtenerAtributoValorXml(String xml, String atributo){
String valor = null;
Document document = convertirStringXml(xml);
Element rootNode = document.getRootElement();
Attribute attribute = rootNode.getAttribute(atributo);
valor = attribute.getValue();
return valor;
}
/**
* Covierte un XML en formato String
* a un objeto de la libreria jdom2
* @param xml xml en formato String
* @return doc Documento XML de jdom2
* @author Jesus Perales.
*/
public static String convertirXmlString(Document doc) {
XMLOutputter xmlOutput = new XMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
String xml = xmlOutput.outputString(doc);
return xml;
}
/**
* Convierte un doc XML de jdom2 a
* una cadena de texto
* @param doc Documento de jdom2
* @return XML en formato cadena de texto
* @author Jesus Perales.
*/
public static Document convertirStringXml(String xml) {
SAXBuilder builder = new SAXBuilder();
Document doc = null;
try {
doc = builder.build(new StringReader(xml));
} catch (JDOMException e) {
LOGGER.error("Error al generar el xml : " + xml);
e.printStackTrace();
} catch (IOException e) {
LOGGER.error("Error al generar el xml : " + xml);
e.printStackTrace();
}
return doc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment