从xml文档

时间:2016-12-26 16:47:32

标签: java xml dom

我正在尝试使用XMLJAVA文档中提取一些标记,我看到了一些与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>

1 个答案:

答案 0 :(得分:2)

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

transform.xslt

$string = preg_replace('/(https?:\/\/)([!#$&-;=?\-\[\]_a-z~%]+)/sim', '<a href="$1$2">$2</a>', 
     preg_replace('/(\s)((www\.)([!#$&-;=?\-\[\]_a-z~%]+))/sim', '$1http://$2', $string)
);

Java代码:

<?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>