【发布时间】:2012-01-14 13:29:38
【问题描述】:
我有一个包含
的字符串形式的 XML<message>HELLO!</message>
我怎样才能得到字符串“你好!”来自 XML?这应该很容易,但我迷路了。 XML 不在文档中,它只是一个字符串。
【问题讨论】:
我有一个包含
的字符串形式的 XML<message>HELLO!</message>
我怎样才能得到字符串“你好!”来自 XML?这应该很容易,但我迷路了。 XML 不在文档中,它只是一个字符串。
【问题讨论】:
使用 JDOM:
String xml = "<message>HELLO!</message>";
org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder();
try {
org.jdom.Document doc = saxBuilder.build(new StringReader(xml));
String message = doc.getRootElement().getText();
System.out.println(message);
} catch (JDOMException e) {
// handle JDOMException
} catch (IOException e) {
// handle IOException
}
使用 Xerces DOMParser:
String xml = "<message>HELLO!</message>";
DOMParser parser = new DOMParser();
try {
parser.parse(new InputSource(new java.io.StringReader(xml)));
Document doc = parser.getDocument();
String message = doc.getDocumentElement().getTextContent();
System.out.println(message);
} catch (SAXException e) {
// handle SAXException
} catch (IOException e) {
// handle IOException
}
使用 JAXP 接口:
String xml = "<message>HELLO!</message>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try {
db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
try {
Document doc = db.parse(is);
String message = doc.getDocumentElement().getTextContent();
System.out.println(message);
} catch (SAXException e) {
// handle SAXException
} catch (IOException e) {
// handle IOException
}
} catch (ParserConfigurationException e1) {
// handle ParserConfigurationException
}
【讨论】:
您还可以使用基本 JRE 提供的工具:
String msg = "<message>HELLO!</message>";
DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(msg.getBytes()));
System.out.println(parse.getFirstChild().getTextContent());
【讨论】:
您可以使用 JAXB 来做到这一点(Java SE 6 中包含一个实现)。
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
String xmlString = "<message>HELLO!</message> ";
JAXBContext jc = JAXBContext.newInstance(String.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
JAXBElement<String> je = unmarshaller.unmarshal(xmlSource, String.class);
System.out.println(je.getValue());
}
}
输出
HELLO!
【讨论】:
上述答案之一表明将 XML 字符串转换为不需要的字节。相反,您可以使用InputSource 并提供StringReader。
String xmlStr = "<message>HELLO!</message>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xmlStr)));
System.out.println(doc.getFirstChild().getNodeValue());
【讨论】:
有做正确的 XML 阅读,或做狡猾的只是为了勉强。 正确的做法是使用正确的文档解析。
或者...狡猾的人会使用自定义文本解析与 wisuzu 的响应或使用带有匹配器的正则表达式。
【讨论】:
我想你会看看String 类,有多种方法可以做到这一点。 substring(int,int) 和 indexOf(int) lastIndexOf(int) 呢?
【讨论】: