0

我正在使用以下代码来解析 XML 文件。但我没有得到任何回应。任何人都可以帮忙吗?

打开连接时,我也会收到警告:

“警告!:调用有问题的方法:找到 java.lang.String.()”`?

public static void main(String arg[]){
    XML_Parsing_Sample application = new XML_Parsing_Sample();
    //create a new instance of the application
    //and start the application on the event thread
    application.enterEventDispatcher();
}

public XML_Parsing_Sample() {
    _screen.setTitle("XML Parsing");//setting title
    _screen.add(new RichTextField("Requesting....."));
    _screen.add(new SeparatorField());
    pushScreen(_screen); // creating a screen
    //creating a connection thread to run in the background
    _connectionthread = new Connection();
    _connectionthread.start();//starting the thread operation
}

public void updateField(String node, String element){
    //receiving the parsed node and its value from the thread
    //and updating it here
    //so it can be displayed on the screen
    String title="Title";
    _screen.add(new RichTextField(node+" : "+element));

    if(node.equals(title)){
        _screen.add(new SeparatorField());
    }
}

private class Connection extends Thread{
    public Connection(){
        super();
    }

    public void run(){
        // define variables later used for parsing
        Document doc;
        StreamConnection conn;

        try{
            //providing the location of the XML file,
            //your address might be different
            conn=(StreamConnection)Connector.open
              ("http://www.w3schools.com/xml/note.xml",Connector.READ);
            //next few lines creates variables to open a
            //stream, parse it, collect XML data and
            //extract the data which is required.
            //In this case they are elements,
            //node and the values of an element
            DocumentBuilderFactory docBuilderFactory
              = DocumentBuilderFactory. newInstance(); 
            DocumentBuilder docBuilder
              = docBuilderFactory.newDocumentBuilder();
            docBuilder.isValidating();
            doc = docBuilder.parse(conn.openInputStream());
            doc.getDocumentElement ().normalize ();
            NodeList list=doc.getElementsByTagName("*");
            _node=new String();
            _element = new String();
            //this "for" loop is used to parse through the
            //XML document and extract all elements and their
            //value, so they can be displayed on the device

            for (int i=0;i<list.getLength();i++){
                Node value=list.item(i).
                  getChildNodes().item(0);
                _node=list.item(i).getNodeName();
                _element=value.getNodeValue();
                updateField(_node,_element);
            }//end for
        }//end try
        //will catch any exception thrown by the XML parser
        catch (Exception e){
            System.out.println(e.toString());
        }
    }//end connection function
}// end connection class
4

3 回答 3

0

您可能正在超时。尝试将连接打开为 HTTP 连接,并使用新ConnectionFactory类摆脱烦人的后缀。

于 2012-05-14T14:19:40.917 回答
0
public InputStream getResult(String url) {
            System.out.println("in get result");
    HttpConnection httpConn;
    httpConn = (HttpConnection) getHTTPConnection(url);
    try {
        if (httpConn != null) {
            final int iResponseCode = httpConn.getResponseCode();
            if (iResponseCode == httpConn.HTTP_OK) {

                _inputStream = httpConn.openInputStream();

                byte[] data = new byte[20];
                int len = 0;
                int size = 0;
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    while (-1 != (len = _inputStream.read(data))) {
                        baos.write(data, 0, len);
                        size += len;
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                InputStream is2 = new ByteArrayInputStream(
                        baos.toByteArray());

                return is2;
            } else {
                return null;
            }
        }
    } catch (IOException e) {
        System.err.println("Caught IOException: " + e.getMessage());
    }
    try {
        httpConn.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

下载 xml 解析下载的 xml。

public Document XMLfromInputStream(InputStream xml) {
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setAllowUndefinedNamespaces(true);
    dbf.setCoalescing(true);
    dbf.setExpandEntityReferences(true);

    try {
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        InputSource _source = new InputSource();
        _source.setEncoding("UTF-8");
        _source.setByteStream(xml);
        db.setAllowUndefinedNamespaces(true);
        doc = db.parse(_source);
    } catch (SAXException e) {
        System.out.println("Wrong XML file structure: " + e.getMessage());
        return null;
    } catch (IOException e) {
        System.out.println("I/O exeption: " + e.getMessage());
        return null;
    } catch (net.rim.device.api.xml.parsers.ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } finally {

    }
    return doc;

}

然后将此文档解析为元素

Element rootElement = document.getDocumentElement();
rootElement.normalize();
displayNode( rootElement, 0 );

private void displayNode( Node node, int depth ) 
{        

    if ( node.getNodeType() == Node.ELEMENT_NODE ) 
    {
        StringBuffer buffer = new StringBuffer();
        indentStringBuffer( buffer, depth );
        NodeList childNodes = node.getChildNodes();
        int numChildren = childNodes.getLength();
        Node firstChild = childNodes.item( 0 );

        // If the node has only one child and that child is a Text node, then it's of 
        // the form  <Element>Text</Element>, so print 'Element = "Text"'.
        if ( numChildren == 1 && firstChild.getNodeType() == Node.TEXT_NODE ) 
        {
            buffer.append( node.getNodeName() ).append( " = \"" ).append( firstChild.getNodeValue() ).append( '"' );
            add( new RichTextField( buffer.toString() ) );
        } 
        else 
        {
            // The node either has > 1 children, or it has at least one Element node child. 
            // Either way, its children have to be visited.  Print the name of the element
            // and recurse.
            buffer.append( node.getNodeName() );
            add( new RichTextField( buffer.toString() ) );

            // Recursively visit all this node's children.
            for ( int i = 0; i < numChildren; ++i ) 
            {
                displayNode( childNodes.item( i ), depth + 1 );
            }
        }
    } 
    else 
    {
        // Node is not an Element node, so we know it is a Text node.  Make sure it is 
        // not an "empty" Text node (normalize() doesn't consider a Text node consisting
        // of only newlines and spaces to be "empty").  If it is not empty, print it.
        String nodeValue = node.getNodeValue();
        if ( nodeValue.trim().length() != 0 ) 
        {
            StringBuffer buffer = new StringBuffer();
            indentStringBuffer( buffer, depth );
            buffer.append( '"' ).append( nodeValue ).append( '"' );
            add( new RichTextField( buffer.toString() ) );
        }
    }
}


/**
 * Adds leading spaces to the provided string buffer according to the depth of 
 * the node it represents.
 * 
 * @param buffer The string buffer to add leading spaces to.
 * @param depth The depth of the node the string buffer represents.
 */
private static void indentStringBuffer( StringBuffer buffer, int depth ) 
{
    int indent = depth * _tab;

    for ( int i = 0; i < indent; ++i ) 
    {
        buffer.append( ' ' );
    }
}

您可以使用上述示例下载并解析 xml。

于 2012-05-15T06:58:15.043 回答
0
NamedNodeMap attributes = (NamedNodeMap)value.getAttributes();
                for (int g = 0; g < attributes.getLength(); g++) {
                    Attr attribute = (Attr)attributes.item(g);
                    System.out.println(" Attribute: " + attribute.getName() +
                    " with value " +attribute.getValue());

上面的代码获取属性及其值..欢呼

于 2012-05-15T11:05:40.540 回答