Reputation: 29
I need to extract (using Java) the tag for the given name tag from XML file like this:
Here is my XML file:
<aa>
<bb>
<name>k1</name>
<value>5</value>
</bb>
<bb>
<name>k2</name>
<value>7</value>
</bb>
</aa>
Input to function: full path to <name> tag, e.g.: /aa/bb/name=k2
( Output for this example should return 7
)
Also more advanced question: I need to extract all name:value pairs from the XML file then the name is given by regular expression I am thinking that XPath is the right tool here, but devil in details.
Upvotes: 2
Views: 1526
Reputation: 3377
Below is the code of extracting value using vtd-xml.
import com.ximpleware.*;
public class extractValue{
public static void main(String s[]) throws VTDException, IOException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", false));
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/aa/bb[name='k1']/value");
int i=0;
while ((i=ap.evalXPath())!=-1){
System.out.println(" value ===>"+vn.toString(i));
}
}
}
Upvotes: 0
Reputation: 1178
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import javax.xml.xpath.XPathExpressionException;
public class XmlParsingTest {
@Test
public void testParsing() throws XPathExpressionException, JDOMException, IOException {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("src/test/resources/yourXMLDoc.xml");
Document origDoc = (Document) builder.build(xmlFile);
XPath xPathMonsOccCategoryIdInOriginalDoc = XPath.newInstance("//bb[name/text()='k2']/value");
Element element = (Element) xPathMonsOccCategoryIdInOriginalDoc.selectSingleNode(origDoc.getRootElement());
assertEquals("7", element.getTextTrim());
}
}
Upvotes: 0
Reputation: 105063
Try jcabi-xml (see this blog post) with a one-liner:
String found = new XMLDocument(text).xpath("/aa/bb[name='k2']/text()").get(0);
Upvotes: 0
Reputation: 149007
You can use the javax.xml.xpath APIs that are included as part of Java SE 5:
import java.io.FileReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression xpe = xpath.compile("//bb[name/text()='k2']/value");
InputSource xml = new InputSource(new FileReader("input.xml"));
String result = xpe.evaluate(xml);
System.out.println(result);
}
}
Upvotes: 2