如何用正则表达式替换java程序中的xml标签和值

时间:2013-11-29 17:54:56

标签: java xml regex

我在java程序中加载XML

<BidirectionalLink>
      <bidirKey>12</bidirKey>
      <upStreamLink>
        <uniLinkKey>1</uniLinkKey>
        <maxBandwidth>0</maxBandwidth>
        <maxReservableBandwidth>0</maxReservableBandwidth>
        <unreservedBandwidth/>
        <maxLspBandwidth/>
        <teMetric>0</teMetric>
        <igpMetric>0</igpMetric>
        <adminGroups>0</adminGroups>
        <ageing>0.0</ageing>
        <bolOverheadLoss>0.0</bolOverheadLoss>
        <patchLoss>0.0</patchLoss>
        <minNumberChannel>0</minNumberChannel>
        <maxNumberChannel>0</maxNumberChannel>
        <linkComponentList>
          <LinkComponent>
            <linkComponentKey>1</linkComponentKey>
            <wdmSpanList>
              <WdmSpan>
                <spanKey>1</spanKey>
                <lenght>0.0</lenght>
                <spanLoss>0.0</spanLoss>

我希望将标签的所有值替换为BidirKey,uniLinkKey,linkComponentKey,spanKey(用&#34; Key&#34;完成)和0.所以,就像那样

<BidirectionalLink>
      <bidirKey>0</bidirKey>
      <upStreamLink>
        <uniLinkKey>0</uniLinkKey>
        <maxBandwidth>0</maxBandwidth>
        <maxReservableBandwidth>0</maxReservableBandwidth>
        <unreservedBandwidth/>
        <maxLspBandwidth/>
        <teMetric>0</teMetric>
        <igpMetric>0</igpMetric>
        <adminGroups>0</adminGroups>
        <ageing>0.0</ageing>
        <bolOverheadLoss>0.0</bolOverheadLoss>
        <patchLoss>0.0</patchLoss>
        <minNumberChannel>0</minNumberChannel>
        <maxNumberChannel>0</maxNumberChannel>
        <linkComponentList>
          <LinkComponent>
            <linkComponentKey>0</linkComponentKey>
            <wdmSpanList>
              <WdmSpan>
                <spanKey>0</spanKey>
                <lenght>0.0</lenght>
                <spanLoss>0.0</spanLoss>

我怎么能这样做我的java?有没有&#34;正则表达式?我不了解它们,我也不知道如何在java程序中使用它们。

我试过这个,但是没有用。最后,temp.xml包含相同的键值。

public void allKeyToZero(String filePath){
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filePath);
            // loop all choosen tags
            List<String> tagsToBeModified = new ArrayList<String>();
            tagsToBeModified.add("Key1");
            tagsToBeModified.add("Key2");
            tagsToBeModified.add("Key3");
            tagsToBeModified.add("Key4");
            tagsToBeModified.add("Key5");
            for (String tagName : tagsToBeModified){
                if (doc.getElementsByTagName(tagName)!=null && doc.getElementsByTagName(tagName).item(0)!=null )
                    doc.getElementsByTagName(tagName).item(0).setTextContent("0");
            }

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("./temp.xml"));
            transformer.transform(source, result);
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SAXException sae) {
            sae.printStackTrace();
        }

    }

1 个答案:

答案 0 :(得分:0)

我建议在这种情况下避免使用正则表达式并使用标准DOM XML Parser,这样您就可以对实际修改的内容有更多的控制权。这是一份工作样本:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class ModifyXMLFile {

    public static void main(String argv[]) {

        try {
            String filepath = "sample.xml";
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);
            // loop all choosen tags
            List<String> tagsToBeModified = new ArrayList<String>();
            tagsToBeModified.add("bidirKey");
            tagsToBeModified.add("uniLinkKey");
            tagsToBeModified.add("linkComponentKey");
            tagsToBeModified.add("spanKey");
            for (String tagName : tagsToBeModified)
                doc.getElementsByTagName(tagName).item(0).setTextContent("0");
            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SAXException sae) {
            sae.printStackTrace();
        }
    }
}

如果您确实需要将所有标记设置为零,并使用name = * key,则可以轻松修改示例以使用 doc.getChildNodes填充 tagsToBeModified 列表循环遍历所有节点( )

有关Java中的XML的更多信息,请查看此http://www.mkyong.com/tutorials/java-xml-tutorials