如何从XML文档中按顺序获取键和值

时间:2015-08-20 05:03:03

标签: java xml parsing xpath

这里我解析给定的XML文档并获取元素节点键和值。但是,我获得这些值的顺序是随机顺序。如何从文档顶部到底部按顺序获取它。

示例:[MonthlyPlanPremiumAmtPP,MonthlyAdvancedPTCAmtPP,MonthCdPP等...]

是因为我的数据结构吗?我正在从Map转换为List。

XML文档:

<Return xmlns="http://www.irs.gov/efile">
  <ReturnData>
    <IRS1095A uuid="a77f40a2-af31-4404-a27d-4c1eaad730c2">
      <MonthlyPTCInformationGrpPP uuid="69dc9dd5-5415-4ee4-a199-19b2dbb701be">
        <MonthlyPlanPremiumAmtPP>136</MonthlyPlanPremiumAmtPP>
        <MonthlyAdvancedPTCAmtPP>125</MonthlyAdvancedPTCAmtPP>
        <MonthCdPP>SEPTEMBER</MonthCdPP>
        <MonthlyPremiumSLCSPAmtPP>250</MonthlyPremiumSLCSPAmtPP>
      </MonthlyPTCInformationGrpPP>
    </IRS1095A>
    <IRS1040>
      <IndividualReturnFilingStatusCd>1</IndividualReturnFilingStatusCd>
      <WagesSalariesAndTipsAmt>22000</WagesSalariesAndTipsAmt>
      <TotalExemptionsCnt>1</TotalExemptionsCnt>
      <AdjustedGrossIncomeAmt>22000</AdjustedGrossIncomeAmt>
    </IRS1040>
  </ReturnData>
  <ReturnHeader>
    <SelfSelectPINGrp>
      <PrimaryBirthDt>1970-01-01</PrimaryBirthDt>
    </SelfSelectPINGrp>
    <Filer>
      <PrimarySSN>555-11-2222</PrimarySSN>
      <PrimaryResidentStatesInfoGrpPP>
        <ResidentStateInfoPP uuid="a77f40a2-af31-4404-a27d-4c1eaad730c2">
          <ResidentStateAbbreviationCdPP>CA</ResidentStateAbbreviationCdPP>
        </ResidentStateInfoPP>
      </PrimaryResidentStatesInfoGrpPP>
    </Filer>
  </ReturnHeader>
</Return>

代码:

@Test
public void testGetXMLModelData() throws Exception {
    File f = new File("xmlDir/example.xml");
    Model m = getXMLModelData(f);

    logger.debug("Models Keys: "+m.getInputs());
    logger.debug("Models Values: "+m.getValues());
}

public Map<String, String> p(File file) throws Exception {

    Map<String, String> map = new HashMap<String,String>();
    XMLStreamReader xr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(file));

    while(xr.hasNext()) {

        int e = xr.next();
        if (e == XMLStreamReader.START_ELEMENT) {
            //Further implementation
        } 
    }
    return map;
}



public Model getXMLModelData(File f) throws Exception { 

    Model model = new Model();

    Map<String,String> map = p(f);
    List<String> listKeys = new ArrayList<String>(map.keySet());
    List<String> listValues = new ArrayList<String>(map.values());

    model.setInputs(listKeys);
    model.setValues(listValues); 


    return model;
}

这是我定义为Model的类:

public class Model {

    public static final int INPUTS_ROW = 5;

    private String topic;
    private List<String> inputs;
    private List<String> values;

    public Model() {
        inputs = new ArrayList<String>();
    }


    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public List<String> getInputs() {
        return inputs;
    }

    public void setInputs(List<String> inputs) {
        this.inputs = inputs;
    }

    public List<String> getValues() {
        return values;
    }

    public void setValues(List<String> values) {
        this.values = values;
    }

}

1 个答案:

答案 0 :(得分:0)

问题是HashMap,因为该数据结构以无序方式列出。解决方案是使用 function SaveEmailContentData() { var emailTemplate = $("#textareaEmailHtmlContent").val(); var emailCategoryID =parseInt($("#ddlSelectCorpSearch").val()); var corporateId = ClientID; var TemplateId = 0; if ('@Model.TemplateID' != 'null' && '@Model.TemplateID' != '0') { TemplateId = parseInt('@Model.TemplateID'); } $.ajax({ url: '../../Setup/Setup/SaveEmailContent', dataType: 'json', type: 'POST', data: JSON.stringify({ EmailContent: emailTemplate,EmailContentID:emailCategoryID, ClientID: corporateId, TempID: TemplateId }), cache: false, contentType: 'application/json; charset=utf-8', success: function (result) { debugger; if (result == "success") { showMessage("Update Successful", "Email Content Successfully Updated"); } else { showMessage("Update Failed", "Email Content could not be Updated"); } }, error: function () { alert("error"); } }); } 将插入顺序保存到地图中,它会从上到下扫描文档。