我正在尝试将字符串拆分两次
String example = response;
String [] array = example.split("<section>");
System.out.println(array[0]);
String [] array2 = example.split("<title>");
System.out.println(array2[2]);
我试图通过使用此代码来实现此目的(未成功),但我不想打印第一个拆分,而是想保存它并继续进行第二个拆分。谁能解决这个问题或更好的方法将字符串分割两次?谢谢
最佳答案
这可能看起来很多...但您确实应该使用 DOM 解析器来操作 XML:
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
public class ExtractXML {
public static void main(String argv[]) {
DocumentBuilderFactory docBuilderFactory = null;
DocumentBuilder docBuilder = null;
Document doc = null;
String rawStr = "Response: <section><title>Input interpretation</title>"
+ "<sectioncontents>Ireland</sectioncontents></section>"
+ "<section><title>Result</title>"
+ "<sectioncontents>Michael D. Higgins</sectioncontents></section>";
String docStr = rawStr.substring(rawStr.indexOf('<'));
String answer = "";
try {
docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilder = docBuilderFactory.newDocumentBuilder();
doc = docBuilder.parse(new InputSource(new StringReader(docStr)));
} catch (SAXParseException e) {
System.out.println("Doc missing root node, adding and trying again...");
docStr = String.format("<root>%s</root>", docStr);
try {
doc = docBuilder.parse(new InputSource(new StringReader(docStr)));
} catch (Exception e1) {
System.out.printf("Malformed XML: %s\n", e1.getMessage());
System.exit(0);
}
} catch (Exception e) {
System.out.printf("Something went wrong: %s\n", e.getMessage());
} finally {
try {
// Normalize text representation:
doc.getDocumentElement().normalize();
NodeList titles = doc.getElementsByTagName("title");
for (int tIndex = 0; tIndex < titles.getLength(); tIndex++) {
Node node = titles.item(tIndex);
if (node.getTextContent().equals("Result")) {
Node parent = node.getParentNode();
NodeList children = parent.getChildNodes();
for (int cIndex = 0; cIndex < children.getLength(); cIndex++) {
Node child = children.item(cIndex);
if (child.getNodeName() == "sectioncontents") {
answer = child.getTextContent();
}
}
}
}
System.out.printf("Answer: %s\n", answer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
输出:
[Fatal Error] :1:98: The markup in the document following the root element must be well-formed.
Doc missing root node, adding and trying again...
Answer: Michael D. Higgins
关于java - 如何将一个字符串分割两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821713/