X Query and XPath
Optimization in XML Parsing through X Query and
XPath
Xquery is XML Query language for query xml data.
You can find more about it http://www.w3schools.com/
XML File
|
StringBuffer xmlSB =
new StringBuffer();
xmlSB.append(" ");
xmlSB.append("
xmlSB.append("
xmlSB.append("");
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append(" ");
xmlSB.append("
");
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append(" ");
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append(" ");
xmlSB.append("
xmlSB.append("
");
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append(" ");
xmlSB.append("
");
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append(" ");
xmlSB.append("
xmlSB.append("
xmlSB.append("
xmlSB.append(" ");
xmlSB.append("");
|
|
File xml =
xmlFile;// xmlFile is reference of xml file.
XmlObject xmlObject =
XmlObject.Factory.parse( xml );
//If Predefined namespace
StringBuffer xQuerySB = new StringBuffer();
xQuerySB.append( " declare namespace
xq='http://www.w3.org/2001/XMLSchema'; " );
xQuerySB.append( " for $e in
$this/xq:catalog/xq:journal " );
xQuerySB.append( " return
$e/journal[@publisher='apress'] " );
XmlObject[] results = xmlObject.execQuery(
xQuerySB.toString() );
|
(1)Execute Query by XmlObject
|
If Setting Default namespace
|
xmlOptions.setUseDefaultNamespace();
XmlObject[] results =
xmlObject.execQuery(xQuerySB.toString(), xmlOptions );
|
If setting multiple namespace
|
XmlOptions xmlOptions = new XmlOptions();
Map
prefixnameSpacehashMap = new hashMap();//If we have multiple schema.
prefixnameSpacehashMap.put(“xq”,”
http://www.w3.org/2001/XMLSchema”);
xmlOptions.setLoadAdditionalNamespaces(prefixnameSpacehashMap
)
XmlObject[] results =
xmlObject.execQuery(xQuerySB.toString(),, xmlOptions );
|
(2)Execute Query by XmlCursor
|
XmlCursor
xmlCursor = xmlObject.newCursor();//Creating new Cursor
StringBuffer xQuerySB = new StringBuffer();
xQuerySB.append( " for $a in
$this/catalog/journal " );
xQuerySB.append( " return
$a/article[@section='Java Technology'] " );
XmlCursor resultCursor =
xmlCursor.execQuery( xQuerySB.toString() );
xmlCursor.selectPath(
"$this/catalog/journal/@publisher" );
while( xmlCursor.toNextSelection() )
{
System.out.println(
xmlCursor.getTextValue() );
}
|
You can parse xml conditionally by using “xmlCursor.selectPath”
References:
http://www.w3.org/2001/XMLSchema, http://xmlbeans.apache.org/
Comments
Post a Comment