Bai_yk的gravatar头像
Bai_yk 2015-07-20 16:33:08

xml文件中字符串带有冒号通过java怎么解析?

类似这样的xml字符串该怎么解析?

<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
    <cas:authenticationSuccess>
        <cas:user>09612</cas:user>
        <cas:attributes>    
            <cas:employeeNumber>09612</cas:employeeNumber>
        </cas:attributes>
    </cas:authenticationSuccess>
</cas:serviceResponse>

我的解析方式用的是DOM,但是root始终未null,现在我要获取背景颜色为黄色的value,该咋解析呢。请教各位牛牛

try {   
                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
                 DocumentBuilder builder = factory.newDocumentBuilder();   
                 Document doc = builder.parse(new InputSource(new StringReader(xmlStr)));   
                 Element root = doc.getDocumentElement();   
                 NodeList books = root.getChildNodes();   
                if (books != null) {   
                    for (int i = 0; i < books.getLength(); i++) {   
                         Node book = books.item(i);   
                         System.out.println("节点=" + book.getNodeName() + "\ttext="  
                                 + book.getFirstChild().getNodeValue());   
                     }   
                 }   
             } catch (Exception e) {   
                 e.printStackTrace();   
             }   
         }   

所有回答列表(2)
最代码官方的gravatar头像
最代码官方  LV167 2015年7月20日

这个问题是考察api的,只要认真按doc来查找相对应的java方法没什么难度,希望以后能自己解决。

package com.xml.resolver;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {

	public static void main(String[] args) throws IOException {
		String xml = FileUtils.readFileToString(new File("c:/a.xml"));
		System.out.println(xml);

		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder
					.parse(new InputSource(new StringReader(xml)));
			Element root = doc.getDocumentElement();
			NodeList nodeList = root
					.getElementsByTagName("cas:authenticationSuccess");
			if (nodeList != null) {
				for (int i = 0; i < nodeList.getLength(); i++) {
					Node book = nodeList.item(i);
					NodeList _nodeList = book.getChildNodes();
					for (int j = 0; j < _nodeList.getLength(); j++) {
						Node _book = nodeList.item(i);
						System.out.println("节点=" + _book.getNodeName()
								+ " text=" + _book.getTextContent());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

输出:

xml文件中字符串带有冒号通过java怎么解析?

评论(1) 最佳答案
kingsword的gravatar头像
kingsword  LV1 2015年7月21日

顶下楼上的,有提供这个解析节点的方法

顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友