gpt4 book ai didi

java - 从 xml 文档中提取标签

转载 作者:行者123 更新时间:2023-12-02 03:09:04 25 4
gpt4 key购买 nike

我正在尝试从 XML 中提取一些标签文档使用 JAVA我看到了一些与 DOM 相关的答案但我不需要标签的值,如下XML我必须提取<MsgHeader>标签

    <MFEP>
<MsgHeader>
<TmStp>2013-12-25T10:52:50</TmStp>
<TrsInf>
<SdrCode>145</SdrCode>
<RcvCode>7777</RcvCode>
<ReqTyp>asd</ReqTyp>
</TrsInf>
</MsgHeader>

<MsgHeader>
<TmStp>2013-12-25T10:52:50</TmStp>
<TrsInf>
<SdrCode>2123</SdrCode>
<RcvCode>323</RcvCode>
<ReqTyp>asd</ReqTyp>
</TrsInf>
</MsgHeader>

<MsgBody>
<AcctInfo>
<BillingNo>asd</BillingNo>
<BillNo>1267</BillNo>
</AcctInfo>
<ServiceType>FixedLine</ServiceType>
</MsgBody>
<MsgFooter>
<Security>
<Signature>asd</Signature>
</Security>
</MsgFooter>

<MsgHeader>
<TmStp>2013-12-25T10:52:50</TmStp>
<TrsInf>
<SdrCode>2</SdrCode>
<RcvCode>3</RcvCode>
<ReqTyp>BILPULRQ</ReqTyp>
</TrsInf>
</MsgHeader>
</MFEP>

输出必须是

    <MsgHeader>
<TmStp>2013-12-25T10:52:50</TmStp>
<TrsInf>
<SdrCode>145</SdrCode>
<RcvCode>7777</RcvCode>
<ReqTyp>asd</ReqTyp>
</TrsInf>
</MsgHeader>

<MsgHeader>
<TmStp>2013-12-25T10:52:50</TmStp>
<TrsInf>
<SdrCode>2123</SdrCode>
<RcvCode>323</RcvCode>
<ReqTyp>asd</ReqTyp>
</TrsInf>
</MsgHeader>

<MsgHeader>
<TmStp>2013-12-25T10:52:50</TmStp>
<TrsInf>
<SdrCode>2</SdrCode>
<RcvCode>3</RcvCode>
<ReqTyp>BILPULRQ</ReqTyp>
</TrsInf>
</MsgHeader>

最佳答案

我知道您不愿意搞乱 XSLT,但它会像这样简单:

转换.xslt

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
<MFEP>
<xsl:apply-templates select="/MFEP/MsgHeader"/>
</MFEP>
</xsl:template>

<xsl:template match="/MFEP/MsgHeader">
<xsl:copy-of select="." />
</xsl:template>

</xsl:stylesheet>

Java代码:

TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("transform.xslt"));
Transformer transformer = factory.newTransformer(xslt);

Source text = new StreamSource(new File("input.xml"));
transformer.transform(text, new StreamResult(new File("output.xml")));

关于java - 从 xml 文档中提取标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com