user1080390
user1080390

Reputation: 471

Matching string to xml data

I pulled two strings from a user input. I need to match one of them to the row ID.

I'm unaware of whether or not I would need to parse the Strings into integers (Perhaps even parse all of my XML data into strings, then look up that data) or if I can use the Strings to directly lookup XML data? Perhaps neither.

Here's an example of what i'm storing in my XML file:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <language>
        <row id="7101">
            <language-from>English</language-from>
            <language-to>Thai</language-to>
            <cost>30.00</cost>
            <comment><![CDATA[out source]]></comment>
        </row>
    </language>
</data>

Upvotes: 0

Views: 360

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347244

You could use xPath query to look up the nodes...

Document xmlDoc = // Load the XML into an DOM document
Node root = xmlDoc.getDocumentElement();

XPathFactory xFactory = XPathFactory.newInstance();
XPath xPath = getXPathFactory().newXPath();
XPathExpression xExpress = getXPath().compile("/data/language/row[language-from='English']");
NodeList nodeList = (NodeList)xExpress.evaluate(root, XPathConstants.NODESET);

I'd personally build a simpler model around the concept to make it easier to call into, but the concept is the same

Upvotes: 1

Vikdor
Vikdor

Reputation: 24134

Looking at the XML document, I suggest you parse the XML document to a set of structured objects, store them in a map for easy lookup, where the key is your search criteria that comes from the user's input. Unless the XML file changes too often, one-time parsing of the document is worth it than any string based searches on it.

I would define a class to hold that information as follows:

class TranslationCost
{
    private int id;
    private String sourceLang;
    private String targetLang;
    private float cost;
    private String comment;
}

Map<Integer, TranslationCost> idTocostMap;

public float calculateCost(int id, int countOfWords)
{
    TranslationCost costObj = idToCostMap.get(id);
    if (null == costObj) {
        // throw exception
    }
    return costObj.getCost() * countOfWords;
}

something like that...

Upvotes: 1

Related Questions