2016-08-20 59 views
-2

的我编辑XML文件是这样的:编辑数千XML数据

<?xml version="1.0"?> 
<rss version="2.0"> 
    <channel> 
    <title>Test Store</title> 
    <link>http://www.example.com</link> 
    <description>An example item from the feed</description> 

    <item> 
     <id>DB_1</id> 
     <title>Diamond Ring</title> 
     <description>The Most Beautiful Diamond Ring</description> 
     <google_product_category>Accessories</google_product_category> 
     <product_type>Rings</product_type> 
     <link>http://www.example.com/rings</link> 
     <image_link>http://www.example.com/ring.jpg</image_link> 
     <condition>new</condition> 
     <availability>in stock</availability> 
     <discount>10.00%</discount> 
     <price>1490.0</price> 
     <brand>ABC</brand> 
     <item_group_id>GROUP_1</item_group_id> 
    </item> 

    <item> 
     <id>DB_2</id> 
     <title>Gold Ring</title> 
     <description>Pretty Gold Ring</description> 
     <google_product_category>Accessories</google_product_category> 
     <product_type>Rings</product_type> 
     <link>http://www.example.com/gold-rings</link> 
     <image_link>http://www.example.com/gold-ring.jpg</image_link> 
     <condition>new</condition> 
     <availability>in stock</availability> 
     <discount>20.00%</discount> 
     <price>500.0</price> 
     <brand>ABC</brand> 
     <item_group_id>GROUP_2</item_group_id> 
    </item> 

</channel> 
</rss> 

你可以看到,在每一个“项目”的元素,有一个元素“打折”。我想将所有元素“折扣”改为“条件”,并使用“新”作为内容。例如:

前:

<discount>10.00%</discount> 

后:

<condition>new</condition> 

对于元素的重命名,我可以简单地使用任何文本编辑器的查找&替换功能。但是,对于元素内容,由于有数千个不同的值(例如10%/ 20%/ 23%/等),所以我找不到将它们全部更改为“新”值的方法。

我应该使用任何想法或工具来进行此类编辑?

谢谢。

+0

你可以使用一种编程语言,你所熟悉和XML解析库在编程语言。看看你的个人资料,PHP将是一个可行的选择 - 它的XML库与其他任何网站一样疯狂,在网络上有很多例子,并且获得结果相对容易。 –

+1

您也可以考虑[XSLT](http://www.w3.org/Style/XSL/)专用于操纵/转换XML文件的专用语言。大多数通用语言 - Java,PHP,Python,VB--都有库来运行XSLT 1.0脚本。然后有像[Saxon和Xalan](http://stackoverflow.com/tags/xslt/info)这样的专用引擎可以运行2.0甚至3.0脚本。 – Parfait

+0

这简直就是<20行代码..很快看到我的提交 –

回答

0

其实这是在Java中使用XPath和VTD-XML的只是10+线...这里是代码

import com.ximpleware.*; 
import java.io.*; 

public class replaceElements2 { 

    public static void main(String[] s) throws VTDException,IOException{ 
     VTDGen vg = new VTDGen(); 
     if (!vg.parseFile("d:\\xml\\rss.xml", false)){ 
      System.out.println("parsing error"); 
      return; 
     } 
     VTDNav vn = vg.getNav(); 
     AutoPilot ap = new AutoPilot(vn); 
     XMLModifier xm = new XMLModifier(vn); 
     ap.selectXPath("/rss/channel/item/discount"); 
     int i=0; 
     byte[] ba="<condition>new</condition>".getBytes(); 
     while((i=ap.evalXPath())!=-1){ 
      xm.remove(); 
      xm.insertAfterElement(ba); 
     } 
     xm.output("d:\\xml\\rss_new.xml"); 
    } 
}