У меня есть следующий ответ XML:Как разобрать и собрать куски текста из ответа XML Java
<?xml version="1.0" encoding="UTF-8"?>
<data>
<MetaData>
<xpath>/Temporary/EIC/HaveInaccurateInfo</xpath>
<enumeration>AtLeastOneConditionTrue</enumeration>
<scenario>TRUE_BECAUSE_OF_ONE_CONDITION</scenario>
<Template>
<Text id="1">You don't qualify because </Text>
<PertinentDataInputNodeNameListInline id="2"
>ApplicableConditions</PertinentDataInputNodeNameListInline>
<Text id="3">.</Text>
</Template>
</MetaData>
<MetaData>
<xpath>/Temporary/EIC/DisqualifiedBecauseAllQualifyingChildrenHaveITIN</xpath>
<scenario>DISQUALIFIED</scenario>
<Template>
<Text id="1">Your eligibility for this credit is not affected since </Text>
<PertinentDataInputNodeNameListInline id="2">ApplicableConditions</PertinentDataInputNodeNameListInline>
<Text id="3">.</Text>
</Template>
</MetaData>
</data>
я хотел бы, чтобы иметь возможность написать некоторый Java-класс, чтобы иметь возможность объединить/построить текстовые узлы под узлом Template
, когда я передаю xpath
и scenario
(таким образом мы узнаем, какой шаблон использовать).
Пример:
public String constructSentence(String xpath, String scenario) {
// some processing here
return constructedSentence;
}
выход:
Вы не имеете права, потому что ApplicableConditions.
и т.д ...
Как я могу сделать это, используя Java? Каков наилучший подход? Любые рекомендации? Я слышал много раз, когда regex для синтаксического анализа xml был бы грехом, я noob, поэтому любая помощь или предложения были бы очень оценены.
Edit:
Хорошо у меня есть что-то здесь, но это, кажется, я строю неполное предложение наряду с полными предложениями.
String h = new String();
List<String> sent = new ArrayList<>();
Document doc = getDocumentXML(xml);
doc.normalize();
System.out.println("Root node: " + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Template");
for (int tmp = 0; tmp < nList.getLength(); tmp++) {
Node nNode = nList.item(tmp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
NodeList nl = nNode.getChildNodes();
for(int j=0; j<nl.getLength(); j++) {
Node node = nl.item(j);
if(nl.item(j).getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) node;
if(e.hasAttribute("id")) {
String nameNode = e.getNodeName();
System.out.println("GetNodeName: "+nameNode);
Integer currentAttrNum = Integer.parseInt(e.getAttribute("id"));
h += e.getTextContent();
System.out.println("Current id num: "+currentAttrNum);
if(e.getNodeType() == Node.ELEMENT_NODE && !e.getNextSibling().hasAttributes()) {
System.out.println("last sibling");
sent.add(h);
}
}
}
}
for(String s : sent) {
System.out.println("Sentence: "+s);
}
}
}
я получаю следующий результат в моем цикле Еогеасп:
Sentence: You don't qualify because
Sentence: You don't qualify because ApplicableConditions
Sentence: You don't qualify because ApplicableConditions.
Sentence: You don't qualify because ApplicableConditions.Your eligibility for this credit is not affected since
Sentence: You don't qualify because ApplicableConditions.Your eligibility for this credit is not affected since ApplicableConditions
Sentence: You don't qualify because ApplicableConditions.Your eligibility for this credit is not affected since ApplicableConditions.
я должен только быть:
Sentence: You don't qualify because ApplicableConditions.
Sentence: Your eligibility for this credit is not affected since ApplicableConditions.
Можете ли вы найти ошибку в моем коде?
Вы можете использовать анализатор xml и выполнить с ним обычную логику –