java中怎样取出XML格式字符串的节点属性

java中怎样取出XML格式字符串的节点属性,第1张

这个可以用正则表达式来实现。。。

要看你xml具体内容,才能确定表达式该怎么写,我给你举个简单的例子

<a><b>hello</b><b>world</b></a>想提取出b标签里面的内容可以用下面的代码实现

import javautilregexMatcher;

import javautilregexPattern;

public class Test {

public static void main(String[] args){

String s = "<a><b>hello</b><b>world</b></a>";

Pattern pattern = Patterncompile("<b>()</b>");

Matcher matcher = patternmatcher(s);

while(matcherfind()){

Systemoutprintln(matchergroup(1));

}

}

}

运行结果:

hello

world

如果很复杂的话。。。可以用专门的解析XML的来解析。。。一般的自己写个正则就可以解决了。。

希望能帮到你。。。仍有问题可以继续追问或者直接HI我。。。

你说的是获取指定id下面的节点属性值吧!

程序如下,其中equal(“”)双引号中的值为节点的属性值

属性值获取如下:

package saxbuilderibmxmlproperty;

import javaioFile;

import javaioIOException;

import javautilIterator;

import orgdom4jAttribute;

import orgdom4jDocument;

import orgdom4jDocumentException;

import orgdom4jElement;

import orgdom4jioSAXReader;

import orgjdomJDOMException;

import orgjdominputSAXBuilder;

public class XmlProperty {

public Element element;

String path = "D:\\xml\\axml";

public void getElementProperty() {

File file = new File(path);

try {

SAXReader reader = new SAXReader();

Document dc = readerread(file);

Element e = dcgetRootElement();

// 节点值

Element child = (Element) egetQName("COMMAND");

Systemoutprintln(childtoString());

// 一级节点

for (Iterator iterator = eelementIterator(); iteratorhasNext();) {

Element el = (Element) iteratornext();

// 一级节点的属性信息

for (Iterator iterator2 = elattributeIterator(); iterator2

hasNext();) {

Attribute attribute = (Attribute) iterator2next();

if(attributegetName()equals("bodyCategory")){

Systemoutprintln("attributegetName()一级节点的属性信息+"+attributegetName()+attributegetValue());

}else{

Systemoutprintln("attributegetName()一级节点的属性信息+"+attributegetName()+attributegetValue());

}

// 二级节点

for (Iterator iterator3 = elelementIterator(); iterator3

hasNext();) {

Element ele = (Element) iterator3next();

// 二级节点的属性信息

for (Iterator iterator4 = eleattributeIterator(); iterator4

hasNext();) {

Attribute attribute1 = (Attribute) iterator4next();

if(attribute1getName()equals("cmdType")){

Systemoutprintln("attribute1getName()二级节点的属性信息+"+attribute1getName()+"+"+attribute1getValue());

}else{

Systemoutprintln("attribute1getName()二级节点的属性信息+"+attribute1getName()+"+"+attribute1getValue());

}

}

}

}

} catch (DocumentException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

}

import w c dom ;

import javax xml parsers ;

import java io ;

public class Parse{

//Document可以看作是XML在内存中的一个镜像 那么一旦获取这个Document 就意味着可以通过对

//内存的 *** 作来实现对XML的 *** 作 首先第一步获取XML相关的Document

private Document doc=null;

public void init(String xmlFile) throws Exception{

//很明显该类是一个单例 先获取产生DocumentBuilder工厂

//的工厂 在通过这个工厂产生一个DocumentBuilder

//DocumentBuilder就是用来产生Document的

DocumentBuilderFactory dbf=DocumentBuilderFactory newInstance();

DocumentBuilder db=dbf newDocumentBuilder();

//这个Document就是一个XML文件在内存中的镜像

doc=db parse(new File(xmlFile));

}

//该方法负责把XML文件的内容显示出来

public void viewXML(String xmlFile) throws Exception{

this init(xmlFile);

//在xml文件里 只有一个根元素 先把根元素拿出来看看

Element element=doc getDocumentElement();

System out println( 根元素为: +element getTagName());

NodeList nodeList=doc getElementsByTagName( dbstore );

System out println( dbstore节点链的长度: +nodeList getLength());

Node fatherNode=em( );

System out println( 父节点为: +fatherNode getNodeName());

//把父节点的属性拿出来

NamedNodeMap attributes=fatherNode getAttributes();

for(int i= ;i<attributes getLength();i++){

Node attribute=em(i);

System out println( dbstore的属性名为: +attribute getNodeName()+ 相对应的属性值为: +attribute getNodeValue());

}

NodeList childNodes = fatherNode getChildNodes();

System out println(childNodes getLength());

for(int j= ;j<childNodes getLength();j++){

Node childNode=em(j);

//如果这个节点属于Element 再进行取值

if(childNode instanceof Element){

//System out println( 子节点名为: +childNode getNodeName()+ 相对应的值为 +childNode getFirstChild() getNodeValue());

System out println( 子节点名为: +childNode getNodeName()+ 相对应的值为 +childNode getFirstChild() getNodeValue());

}

}

}

public static void main(String[] args)throws Exception{

Parse parse=new Parse();

//我的XML文件

parse viewXML( netct xml );

}

lishixinzhi/Article/program/Java/hx/201311/26710

实现思路:可以通过w3c的dom解析器进行 *** 作,之后通过getName获取到xmltpye中的属性值。

举例:

import javaioFile;

import javaxxmlparsersDocumentBuilder;

import javaxxmlparsersDocumentBuilderFactory;

import orgw3cdomDocument;

import orgw3cdomElement;

import orgw3cdomNodeList;

public class DomTest1

{

public static void main(String[] args) throws Exception

{

// step 1: 获得dom解析器工厂(工作的作用是用于创建具体的解析器)

DocumentBuilderFactory dbf = DocumentBuilderFactorynewInstance();

// Systemoutprintln("class name: " + dbfgetClass()getName());

// step 2:获得具体的dom解析器

DocumentBuilder db = dbfnewDocumentBuilder();

// Systemoutprintln("class name: " + dbgetClass()getName());

// step3: 解析一个xml文档,获得Document对象(根结点)

Document document = dbparse(new File("candidatexml"));

NodeList list = documentgetElementsByTagName("PERSON");

for(int i = 0; i < listgetLength(); i++)

{

Element element = (Element)listitem(i);

String content = elementgetElementsByTagName("NAME")item(0)getFirstChild()getNodeValue();

Systemoutprintln("name:" + content);

Systemoutprintln("--------------------------------------");

}

}

}

创建解析器

SAXReader saxreader = new SAXReader();

读取文档

Document doc = saxreaderread(new File("url"));

获取根

Element root = docgetRootElement();

获取子节点

List<Element> list = rootelements();

Systemoutprintln(eelementText("name"));

Systemoutprintln(eelement("score")attributeValue("java"));

Reader reader = new InputStreamReader(con

getInputStream());

SAXReader sax = new SAXReader();

// saxsetEncoding("GBK");

Document document = saxread(reader);

documentsetXMLEncoding("GBK");

Element root = documentgetRootElement();

// Document doc = readerread(read);

// Element root = docgetRootElement();

readNode(root, "");

public static void readNode(Element root, String prefix) {

if (root == null) return;

// 获取属性

List<Attribute> attrs = rootattributes();

if (attrs != null && attrssize() > 0) {

Systemerrprint(prefix);

for (Attribute attr : attrs) {

Systemerrprint(attrgetValue() + " ");

}

Systemerrprintln();

}

// 获取他的子节点

List<Element> childNodes = rootelements();

prefix += "\t";

for (Element e : childNodes) {

//输出内容

Systemerrprintln(egetName()+":"+egetData());

readNode(e, prefix);

}

}

1、用 childNodes 属性,按顺序取

实现过程:首先创建一个 xml 对象,然后载入 xml 文件,再根据待取节点父节点在 xml 文件中的序号和本身的序号,确定待取节点的位置,最后返回待取节点的值。

//pId 待取节点父节点序号

//cId 待取节点序号

function getXmlNodeValue(pId, cId) {

var xmlDoc = new ActiveXObject("MicrosoftXMLDOM");

xmlDocasync = false;

xmlDocload("employeeInfoxml");

var nodes = xmlDocdocumentElementchildNodes[pId]childNodes[cId];return nodeschildNodes[0]text;

}

调用方法:alert(getXmlNodeValue(1, 2));

2、用 for 循环来取

实现过程:首先创建一个 ie 支持的 xml 对象,如果发生异常,是创建一个 FireFox 支持的空 xml 对象并返回空;然后载入 xml 文件,如要发生异常也返回空;最后,通过 for 循环遍历查找与传入的节点值相同的节点,找到后返回属于该节点的属性值。

//nodeValue 待取节点的所属节点值

function getXmlNodeValueFor(nodeValue){

var xmlDoc; 

try { 

//创建一个 ie 支持的 XML 文档对象 

xmlDoc = new ActiveXObject("MicrosoftXMLDOM");

}catch(e){

try{

//创建FireFox空的XML文档对象

xmlDoc=documentimplementationcreateDocument("","",null);

}catch(e){

alert(emessage);

return "";

}

}

xmlDocasync = false;

try { 

xmlDocload("employeeInfoxml");

}catch(e){

alert(emessage);

return "";

}

var xd=xmlDocdocumentElementchildNodes;

if(xd==null)

return "";

var tempValue;

for(var i=0;i<xdlength;i++){

if(xd[i]childNodes[0]childNodes[0]nodeValue==nodeValue) tempValue=xd[i]childNodes[2]childNodes[0]nodeValue;

}

return tempValue;

}

调用方法:alert(getXmlNodeValueFor("王佳琳"));

以上就是关于java中怎样取出XML格式字符串的节点属性全部的内容,包括:java中怎样取出XML格式字符串的节点属性、java语句如何获取XML文件的节点值、JAVA读取xml文件中节点值等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/9750972.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-01
下一篇2023-05-01

发表评论

登录后才能评论

评论列表(0条)

    保存