String Operation to get particular value inside the string using java
I have a string as below.
<employees>
<emp>
<name>yaakobu</name>
<sal>$20000</sal>
<designation>Manager</designation>
</emp>
<emp>
<name>daaniyelu</name>
<sal>$2000</sal>
<designation>Operator</designation>
</emp>
<emp>
<name>paadam</开发者_开发技巧name>
<sal>$7000</sal>
<designation>Engineer</designation>
</emp>
</employees>
The above xml i am getting as a string.i was asked not to use parsing due to performance issue.I need to get the second employee 's salary($2000) using java's string operation.Please provide me some pointers.
Your help appreciated.
Your string is xml. Although it might be tempting to use regex or other string manipulation to extract data from xml - don't do it - it's a bad practice.
You should use some XML parser instead.
After you've done this using your string operations, give the following a try:
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
public class Main {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("test.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
// get the salary from the employee at index 1
XPathExpression expr = xpath.compile("//emp[1]/sal");
Object salary = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(salary);
}
}
which should output:
$20000
I'm not guaranteeing it will be faster, but it won't differ all that much I think. And doing it like this will be far less fragile than doing this with indexOf(...)
and substring(...)
calls.
I doubt there will be performance issues using an xml
parser, but if you want to do it by string parsing, use str.indexOf("<sal>", str.indexOf("<sal>") + 5);
Then it will be easy.
Use xml parser or JAXB api for unmarshal the String into object, you can do it through this way also.
private static Object getObject(String yourXml) throws Exception {
JAXBContext jcUnmarshal = null;
Unmarshaller unmarshal = null;
javax.xml.stream.XMLStreamReader rdr = null;
//Object obj = null;
try {
jcUnmarshal = JAXBContext.newInstance("com.test.dto");
unmarshal = jcUnmarshal.createUnmarshaller();
rdr = javax.xml.stream.XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(yourXml));
//obj = (Object) unmarshal.unmarshal(rdr);
return (Object) unmarshal.unmarshal(rdr);
} catch (JAXBException jaxbException) {
jaxbException.printStackTrace();
log.error(jaxbException);
throw new ServiceException(jaxbException.getMessage());
}
finally{
jcUnmarshal = null;
unmarshal = null;
rdr.close();
rdr = null;
}
//return obj;
}
you might use xstream http://x-stream.github.io/ you put your xml in an object structure and get it from there.
check the samples ,is very easy to use
This if you don't want to parse yourself...:)
精彩评论