2016-04-25 2 views
0

У меня есть следующий ответ 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. 

Можете ли вы найти ошибку в моем коде?

+1

Вы можете использовать анализатор xml и выполнить с ним обычную логику –

ответ

0

Я мало знаю о XML (и, во многом, я ничего не имею в виду), но я постараюсь помочь. Если вы получаете вывод текста вы можете return в Java, вы можете взять этот текст и сделать что-то вдоль линий

/*regexNameHere is the name you give the array, inputTextVar is the variable 
*(make sure it's a string!) assigned to the text you receive from the XML process 
*/ 
String [] (regexNameHere) = (inputTextVar).split("character to split by"); 
//This is what you use to declare variables... 
String var1 = regexNameHere[0]; 
String var2 = regexNameHere[1]; 

И так далее. Если переменная regexNameHere была равна строке «Строка разделения Regex», а аргумент .split равен (" ") (пробел), то regexNameHere[0] будет равен «Regex», regexNameHere[1] будет «разделен», а regexNameHere[2] будет «string».

Если вы хотите разделить что-то вроде «ApplicableConditions» в тексте, я предположил бы, что вы просто поставить «Применимым» как .split аргумента, и regexNameHere[0] будет равен «Применим» и regexNameHere[1] будет равен «Условие».

Надеюсь, что это помогло, и удачи!

Смежные вопросы