简体   繁体   English

如何使用Java中的节点属性值读取,更新和删除现有XML文件

[英]How to read, update and delete the existing XML file using node attribute value in Java

I am trying to read/update/delete the XML file on the basis of value found. 我试图根据找到的值读取/更新/删除XML文件。

I have a XML with name 123456.xm l with below format. 我有一个名称为123456.xm的XML,格式如下。

<ps>
  <p n="359" u="/ae/arabic/plan_book/plan_and_book.aspx"/>
  <p n="277" u="/ae/english/plan_book/plan_and_book.aspx"/>
  <p n="410" u="/ao/english/plan_book/plan_and_book.aspx"/>
</ps>

Now my new method in java will get Filepath ( c://java/Files/12345.xml ), n(277 - the value which will be checked in file) and U ("/de/english/plan_book/plan_and_book.aspx"). 现在我在java中的新方法将获得Filepath( c://java/Files/12345.xml ),n(277 - 将在文件中检查的值)和U(“/ de/english/plan_book/plan_and_book.aspx “)。

Logic for my java method will as below, but really don't know how to write. 我的java方法的逻辑如下,但实际上不知道如何编写。

Adding/Appending Method Logic: 添加/附加方法逻辑:

  1. Open the file c://java/Files/12345.xml 打开文件c://java/Files/12345.xml
  2. Search for all nodes and find the basis of value of n(277). 搜索所有节点并找到n的值的基础(277)。 There will be only one record for 277 277只有一条记录
  3. If this value exists in the file then no updates are required else add the new node in xml file, so for example if the value of n would have been (777), as this attribute record does not exists in file then it would have added a new record in file ( <pn="777" u="/ao/english/plan_book/plan_and_book.aspx"/> ). 如果文件中存在此值,则不需要更新,否则在xml文件中添加新节点,例如,如果n的值为(777),因为该属性记录在文件中不存在,那么它将添加文件中的新记录( <pn="777" u="/ao/english/plan_book/plan_and_book.aspx"/> )。
  4. Save the updated XML on same location. 将更新的XML保存在同一位置。

Deleting Method Logic: 删除方法逻辑:

  1. Open the file c://java/Files/12345.xml 打开文件c://java/Files/12345.xml
  2. Search for all nodes and find on the basis of value of n(277). 搜索所有节点并根据n的值(277)查找。 There will be only one record for 277. 277只有一条记录。
  3. If this value exists in node attribute "n" then it will delete that node from the xml, else no update required. 如果此值存在于节点属性“n”中,则它将从xml中删除该节点,否则不需要更新。
  4. Save the updated XML on same location. 将更新的XML保存在同一位置。

Would appreciate if you share some good example or links for above implementaion. 如果您分享一些很好的示例或上述实现的链接,将不胜感激。

Thanks. 谢谢。

This kind of processing is usually easier and simpler (no regEx required) to specify in XSLT than in an imperative language . 在XSLT中指定的这种处理通常比在命令式语言中更容易和更简单(不需要regEx)

The XSLT transformation below can be used directly, or it can give an idea how to implement the same algorithm in another language: 下面的XSLT转换可以直接使用,也可以给出如何用另一种语言实现相同算法的想法:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pAction" select="'delete'"/>
 <xsl:param name="pN" select="277"/>
 <xsl:param name="pU" select="'/de/english/plan_book/plan_and_book.aspx'"/>

 <xsl:template match="node()|@*" name="identity">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="ps">
  <ps>
    <xsl:apply-templates select=
     "*[not($pAction = 'delete')]
     |
      *[$pAction = 'delete' and not(@n = $pN)]
     "/>
    <xsl:if test="$pAction = 'add' and not(p[@n = $pN])">
      <p n="{$pN}" u="{$pU}"/>
    </xsl:if>
  </ps>
 </xsl:template>

 <xsl:template match="p">
  <xsl:choose>
    <xsl:when test="not(@n = $pN)">
      <xsl:call-template name="identity"/>
    </xsl:when>
    <xsl:otherwise>
      <xsl:if test="not($pAction = 'delete')">
          <xsl:call-template name="identity"/>
      </xsl:if>
     </xsl:otherwise>
  </xsl:choose>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the provided XML document: 在提供的XML文档上应用此转换时:

<ps>
    <p n="359" u="/ae/arabic/plan_book/plan_and_book.aspx"/>
    <p n="277" u="/ae/english/plan_book/plan_and_book.aspx"/>
    <p n="410" u="/ao/english/plan_book/plan_and_book.aspx"/>
</ps>

the wanted, correct result is produced: 产生了想要的正确结果:

<ps>
   <p n="359" u="/ae/arabic/plan_book/plan_and_book.aspx"/>
   <p n="410" u="/ao/english/plan_book/plan_and_book.aspx"/>
</ps>

when the parameter $pAction is changed to : 当参数$pAction更改为

 <xsl:param name="pAction" select="''add'"/>

then the result of the transformation is the same XML document (unchanged). 然后转换的结果是相同的XML文档(未更改)。

When the parameter is : 当参数是

 <xsl:param name="pAction" select="''add'"/>

and the XML document is : 并且XML文档是

<ps>
    <p n="359" u="/ae/arabic/plan_book/plan_and_book.aspx"/>
    <p n="410" u="/ao/english/plan_book/plan_and_book.aspx"/>
</ps>

then the result is : 然后结果是

<ps>
   <p n="359" u="/ae/arabic/plan_book/plan_and_book.aspx"/>
   <p n="410" u="/ao/english/plan_book/plan_and_book.aspx"/>
   <p n="277" u="/de/english/plan_book/plan_and_book.aspx"/>
</ps>

If and only if your XML is as simple as that sample you provided, you may use this: 当且仅当您的XML与您提供的示例一样简单时,您可以使用:

Following code would iterate over all matches of <p> elements: 以下代码将迭代<p>元素的所有匹配:

try {
    Pattern regex = Pattern.compile("(?is)(<p n=\"(\\d+)\" u=\"([^\"<>]+?)\"/>)");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        // matched text: regexMatcher.group()
        // match start: regexMatcher.start()
        // match end: regexMatcher.end()
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}

To find a specific node (better to say string) with a given number, use this syntax: 要查找具有给定数字的特定节点(更好地说是字符串),请使用以下语法:

(?is)(<p n="#num_to_find#" )(u="[^"<>]+?"/>)

Where alter #num_to_find# with the number you choose. 使用您选择的号码改变#num_to_find# And then could replace like: 然后可以替换为:

$1#string_to_replacewith##

Regex Explanation 正则表达式解释

"(?is)" +                       // Match the remainder of the regex with the options: case insensitive (i); dot matches newline (s)
"(" +                           // Match the regular expression below and capture its match into backreference number 1
   "<p\\ n=\"#num_to_find#\"\\ " +     // Match the characters “<p n="#num_to_find#" ” literally
")" +
"(" +                           // Match the regular expression below and capture its match into backreference number 2
   "u=\"" +                         // Match the characters “u="” literally
   "[^\"<>]" +                      // Match a single character NOT present in the list “"<>”
      "+?" +                          // Between one and unlimited times, as few times as possible, expanding as needed (lazy)
   "\"/>" +                         // Match the characters “"/>” literally
")"  

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM