Ahmad Alkhatib
Ahmad Alkhatib

Reputation: 1226

Extract tags from xml document

I'm trying to extract some tags from XML document using JAVA and I saw some answers related to DOM but I don't need the value of the tag, the following XML which I have to extract <MsgHeader> Tag

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

And the output must be

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

Upvotes: 0

Views: 133

Answers (1)

Rafael Z.
Rafael Z.

Reputation: 1162

I know you are not willing to mess around XSLT, but it would be as simple as this:

transform.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 code:

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

Upvotes: 2

Related Questions