java中获取XML中的子xml_如何将子元素从XML提取到Java中的字符串?

小编典典

没错,使用标准XML API并不是一种好方法-这是一个示例(可能是bug缠身;它可以运行,但是我很久以前就写了)。

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());

}

}

似乎您可以仅使用doc.getDocumentElement()。getFirstChild()来获得第一个孩子,但是问题是如果根元素和子元素之间存在任何空格,则会在树,您将获得该节点,而不是实际的元素节点。该程序的输出为:

D:\home\tmp\xml>java Proc

blahblah

我认为您可以在不需要的情况下取消xml版本字符串,但是我不确定。如果可能的话,我可能会尝试使用第三方XML库。

2020-10-15

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值