简体   繁体   中英

How to store values in an array (Java)

I have a table ( REQUESTS ) and it contains 1 column ( XML_DATA ) for xmls.

So if ID=123 has a row in this table, it should get the corresponding xml.

If xml was retrieved, i need to get all the values with tag <Mobile>0918xxxx</Mobile> .

Here is what i have so far:

for (int i = 0; i < RqeuestsDBViewData.length; i++) //GETS ROWS FROM TABLE REQUESTS
{
    xmlDetails = test.getDetailsFromXML(mCustUtils, RequestDBViewData[i]); //GETS XML FROM XML_DATA
    String strXmlDetails;
    String strMob;
        if (!AppUtils.isEmpty(xmlDetails)) //IF IT HAS ROW, THEN GET RECORD FROM <MOBILE></MOBILE> TAG
        {
             strXmlDetails = xmlDetails.toString(); //ENTIRE XML
             strMob = StringUtils.substringBetween(strXmlDetails, "<Mobile>", "</Mobile>"); //GETS MOBILE VALUE
        }

Now, if there are more than 1 <Mobile></Mobile> ,

i need to store it in an array using for loop.

How do i store multiple values of strMob in an array?

After stroring all possible strMob, i'm planning to assign the values somewhere else like: personalInfo[j].setMobile(array/list[j]);

Any suggestions on how to do this?

Use a proper XML tool to read your XML.

Variant 1

Use Jackson to parse your XML to a prepared Java object . This will also work for arrays.

Variant 2

Read XML to a DOM object

public static Element getDocument(String xmlString) {
    return getDocument(new ByteArrayInputStream(xmlString.getBytes()));
}

public static Element getDocument(InputStream inputStream) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        Document doc = docBuilder.parse(new BufferedInputStream(inputStream));
        Element root = doc.getDocumentElement();
        root.normalize();
        return root;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

With the aim of XPATH you can than extract your <Mobile> elements. See this answer: Extract content between XML tags

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM