He pasado el último día intentando extraer un nodo XML del siguiente documento y no puedo comprender los matices de los espacios de nombres XML para que funcione.XPath, XML Namespaces y Java
El archivo XML es grande para colocar en total, de modo que aquí es la parte que me preocupa:
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<XFDL xmlns="http://www.PureEdge.com/XFDL/6.5" xmlns:custom="http://www.PureEdge.com/XFDL/Custom" xmlns:designer="http://www.PureEdge.com/Designer/6.1" xmlns:pecs="http://www.PureEdge.com/PECustomerService" xmlns:xfdl="http://www.PureEdge.com/XFDL/6.5">
<globalpage sid="global">
<global sid="global">
<xmlmodel xmlns:xforms="http://www.w3.org/2003/xforms">
<instances>
<xforms:instance id="metadata">
<form_metadata>
<metadataver version="1.0"/>
<metadataverdate>
<date day="05" month="Jul" year="2005"/>
</metadataverdate>
<title>
<documentnbr number="2062" prefix.army="DA" scope="army" suffix=""/>
<longtitle>HAND RECEIPT/ANNEX NUMBER </longtitle>
</title>
El documento continúa y está bien formado hasta el fondo. Estoy intentando extraer el atributo "número" de la etiqueta "documentnbr" (tres desde abajo).
El código que estoy usando para hacer esto es el siguiente:
/***
* Locates the Document Number information in the file and returns the form number.
* @return File's self-declared number.
* @throws InvalidFormException Thrown when XPath cannot find the "documentnbr" element in the file.
*/
public String getFormNumber() throws InvalidFormException
{
try{
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new XFDLNamespaceContext());
Node result = (Node)xPath.evaluate(QUERY_FORM_NUMBER, doc, XPathConstants.NODE);
if(result != null) {
return result.getNodeValue();
} else {
throw new InvalidFormException("Unable to identify form.");
}
} catch (XPathExpressionException err) {
throw new InvalidFormException("Unable to find form number in file.");
}
}
Dónde QUERY_FORM_NUMBER es mi expresión XPath, y XFDLNamespaceContext implementa NamespaceContext y se ve así:
public class XFDLNamespaceContext implements NamespaceContext {
@Override
public String getNamespaceURI(String prefix) {
if (prefix == null) throw new NullPointerException("Invalid Namespace Prefix");
else if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX))
return "http://www.PureEdge.com/XFDL/6.5";
else if ("custom".equals(prefix))
return "http://www.PureEdge.com/XFDL/Custom";
else if ("designer".equals(prefix))
return "http://www.PureEdge.com/Designer/6.1";
else if ("pecs".equals(prefix))
return "http://www.PureEdge.com/PECustomerService";
else if ("xfdl".equals(prefix))
return "http://www.PureEdge.com/XFDL/6.5";
else if ("xforms".equals(prefix))
return "http://www.w3.org/2003/xforms";
else
return XMLConstants.NULL_NS_URI;
}
@Override
public String getPrefix(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterator getPrefixes(String arg0) {
// TODO Auto-generated method stub
return null;
}
}
I' he intentado muchas consultas XPath diferentes, pero sigo sintiendo que esto debería funcionar:
protected static final String QUERY_FORM_NUMBER =
"/globalpage/global/xmlmodel/xforms:instances/instance" +
"/form_metadata/title/documentnbr[number]";
Desafortunadamente, no funciona y recibo continuamente un retorno nulo.
He hecho una buena cantidad de lectura here, here y here, pero nada ha sido suficientemente esclarecedor para ayudarme a conseguir este funcionamiento.
Estoy casi seguro de que me voy a enfrentar a la palma de la mano cuando descubro esto, pero estoy realmente al borde de la muerte.
Gracias por leer todo esto y gracias de antemano por la ayuda.
-Andy
La solución perfecta, todavía no entiendo muy bien los espacios de nombres, pero al al menos el código funciona ahora. Muchas gracias. – MrWizard54
@Jason: "No terminé necesitando usar espacios de nombres en la expresión por algún motivo". En la implementación estándar de Java, DocumentBuilderFactory produce namespace-_unaware_ parsers de forma predeterminada. Agregar 'dbfac.SetNamespaceAware (true)' antes de generar DocumentBuilder puede cambiar los resultados. –