關於如何在Java中解決字符串問題的問題

[英]A question on how to solve the string problem in Java


I've created a simple xml file here:

我在這里創建了一個簡單的xml文件:

http://roberthan.host56.com/productsNew.xml

http://roberthan.host56.com/productsNew.xml

which is quite simple, the root node is [products] while all other element nodes are [product]. Under each [product] node, there are two child nodes, [code] and [name], so it basically looks like:

很簡單,根節點是[products],而所有其他元素節點都是[product]。在每個[product]節點下,有兩個子節點[code]和[name],因此基本看起來是:

[product]
     [code]ddd[/code]
     [name]ssss[/name]
   [/product]

I've also written up the following Java code to parse this XML file and take out the text content of the [product] node, and add it to a JComboBox.

我還編寫了以下Java代碼來解析這個XML文件並取出[product]節點的文本內容,並將其添加到JComboBox中。

docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse("http://roberthan.host56.com/productsNew.xml");

    NodeList productNodes = doc.getElementsByTagName("product");

        productlist.clear();
        for (i = 0; i < productNodes.getLength(); i++) 
        {


            Node childNode = productNodes.item(i);

            if (childNode.hasChildNodes()) {
                NodeList nl = childNode.getChildNodes();


                Node nameNode = nl.item(2);
                productlist.add(nameNode.getTextContent());

            }

        }


final JComboBox productComboB = new JComboBox();
Iterator iterator = productlist.iterator();

while(iterator.hasNext())
{
 productComboB.addItem(iterator.next().toString());
}

The code is quite straightforward, I firstly parse the xml and get all the product nodes and put them into a nodelist, and the productList is an arrayList. I loop through the all the [product] nodes, for each of them, if it has child nodes, then I take the second child node (which is the [name] node) and put the text content of it in the array list, and finally, I loop through the arrayList and add each item to the combo box.

代碼非常簡單,我首先解析xml並獲得所有產品節點並將它們放入nodelist,而productList是一個arrayList。我遍歷所有的[產品]節點,為每一個,如果它有子節點,然后我把第二子節點([名字]節點),把數組中的文本內容的列表,最后,我遍歷了arrayList並將每個條目添加到組合框。

The problem I got is, if I select the [code] child node, which means "Node nameNode = nl.item(1)", it will work perfectly; however, if I change that item(1) to item(2) to extract all the [name] nodes, the combo box will have a drop down list, but all the items are blank, like I have inserted 10 empty strings.

我得到的問題是,如果我選擇[code]子節點,這意味着“節點nameNode = nl.item(1)”,它會完美地工作;但是,如果我將該項(1)更改為項(2)以提取所有[name]節點,組合框將有一個下拉列表,但是所有項都是空白的,就像我插入了10個空字符串一樣。

Also, if I try to add a "Hello World" string into the combo box after the above code, the "Hello World" item will appear after the 10 empty items.

另外,如果我嘗試在上面的代碼之后添加一個“Hello World”字符串到組合框中,那么“Hello World”項將會出現在10個空項之后。

I have spent the whole afternoon debugging this but still no breakthrough, the XML is actually quite simple and the Java is straightforward too. Could anyone share some thoughts with me on this please. Thanks a lot!

我花了整個下午調試這個,但仍然沒有突破,XML實際上很簡單,Java也很簡單。有人能和我分享一下這個想法嗎?謝謝!

2 个解决方案

#1


4  

It is because the node list contains text nodes also.

這是因為節點列表也包含文本節點。

If you add the following snippet to your code you will find that

如果您將以下代碼片段添加到代碼中,您將發現這一點

for(int j = 0;j<nl.getLength();j++){
    System.out.println(nl.item(j).getNodeName());
}

It will give the following output for each iteration of the product

它將為產品的每次迭代提供以下輸出

#text
code
#text
name
#text

This means you have to get the 3rd element to get the name node.

這意味着您必須獲得第3個元素來獲取名稱節點。

Node nameNode = nl.item(3);

But I'll suggest you to use XPath to solve this problem.

但是我建議您使用XPath來解決這個問題。

NodeList nodelist = XPathAPI.selectNodeList(doc, "//products/product/name");
for (int i = 0; i < nodelist.getLength(); i++) {
    productlist.add(nodelist.item(i).getTextContent());
}

#2


1  

XPath using this expression will easily solve your problem:

使用此表達式的XPath很容易解決您的問題:

String XPATH_EXPRESSION1 = "//name/text()";

e.g.,

例如,

  public static final String PRODUCTS_NEW = "http://roberthan.host56.com/productsNew.xml";
  public static final String XPATH_EXPRESSION1 = "//name/text()";

  public XmlFun() {
     URL productsUrl;
     try {
        productsUrl = new URL(PRODUCTS_NEW);
        List<String> nameList = xPathExtract(productsUrl.openStream());
     } catch (MalformedURLException e) {
        e.printStackTrace();
     } catch (IOException e) {
        e.printStackTrace();
     } catch (ParserConfigurationException e) {
        e.printStackTrace();
     } catch (SAXException e) {
        e.printStackTrace();
     } catch (XPathExpressionException e) {
        e.printStackTrace();
     }
  }

  private List<String> xPathExtract(InputStream inStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
     DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
     DocumentBuilder builder = domFactory.newDocumentBuilder();
     Document domDoc = builder.parse(inStream);

     XPathFactory xFactory = XPathFactory.newInstance();
     XPath xpath = xFactory.newXPath();

     XPathExpression xExpr = xpath.compile(XPATH_EXPRESSION1);
     NodeList nodes = (NodeList)xExpr.evaluate(domDoc, XPathConstants.NODESET);

     List<String> resultList = new ArrayList<String>();
     for (int i = 0; i < nodes.getLength(); i++) {
        String node = nodes.item(i).getNodeValue();
        resultList.add(node);
     }

     return resultList;
  }

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/12/17/3a024291c845899ad0e02b585c075429.html



 
  © 2014-2022 ITdaan.com 联系我们: