java xml字符串提取元素,如何從XML中將子元素提取到Java中的字符串中?

7

You're right, with the standard XML API, there's not a good way - here's one example (may be bug ridden; it runs, but I wrote it a long time ago).

您是對的,使用標准的XML API,沒有一種好的方法——這里有一個例子(可能是錯誤驅動的;它運行,但我很久以前就寫了。

import javax.xml.*;

import javax.xml.parsers.*;

import javax.xml.transform.*;

import javax.xml.transform.dom.*;

import javax.xml.transform.stream.*;

import org.w3c.dom.*;

import java.io.*;

public class Proc

{

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

{

//Parse the input document

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(new File("in.xml"));

//Set up the transformer to write the output string

TransformerFactory tFactory = TransformerFactory.newInstance();

Transformer transformer = tFactory.newTransformer();

transformer.setOutputProperty("indent", "yes");

StringWriter sw = new StringWriter();

StreamResult result = new StreamResult(sw);

//Find the first child node - this could be done with xpath as well

NodeList nl = doc.getDocumentElement().getChildNodes();

DOMSource source = null;

for(int x = 0;x < nl.getLength();x++)

{

Node e = nl.item(x);

if(e instanceof Element)

{

source = new DOMSource(e);

break;

}

}

//Do the transformation and output

transformer.transform(source, result);

System.out.println(sw.toString());

}

}

It would seem like you could get the first child just by using doc.getDocumentElement().getFirstChild(), but the problem with that is if there is any whitespace between the root and the child element, that will create a Text node in the tree, and you'll get that node instead of the actual element node. The output from this program is:

看起來像你可以第一個孩子只是通過使用doc.getDocumentElement().getFirstChild(),但問題是如果有任何空格之間的根和子元素,將創建一個文本節點的樹,你會得到該節點,而不是實際的元素節點。本程序輸出為:

D:\home\tmp\xml>java Proc

blahblah

I think you can suppress the xml version string if you don't need it, but I'm not sure on that. I would probably try to use a third party XML library if at all possible.

我認為如果不需要xml版本字符串,可以將它隱藏起來,但我不確定。如果可能的話,我可能會嘗試使用第三方XML庫。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值