简体   繁体   English

正则表达式-查找与另一个标记值一起出现的XML标记

[英]regex - find XML tag that occurs together with another tag value

Let's say I have XML: <Customer><CustomerType>Business</CustomerType><CreditRating>Good</CreditRating></Customer> <Customer><CustomerType>Residential</CustomerType><CreditRating>Good</CreditRating></Customer> 假设我有XML: <Customer><CustomerType>Business</CustomerType><CreditRating>Good</CreditRating></Customer> <Customer><CustomerType>Residential</CustomerType><CreditRating>Good</CreditRating></Customer>

and I want to change all the Credit Ratings for the Residential consumers from Good to Bad. 我想将所有住宅消费者的信用等级从“良好”更改为“不良”。

What regex search term can I use to find (and therefore replace) the CreditRating tag only when this occurs within a customer record with a residential Customer Type? 仅当出现在具有固定客户类型的客户记录中时,才可以使用哪个正则表达式搜索词查找(并替换)CreditRating标签?

I know I can use: <Customer>.*?<CustomerType>Residential.*?</Customer> to match a whole record Residential customer record but I only want to match the CreditRating tag within the Customer Record so I can do a search and replace. 我知道我可以使用: <Customer>.*?<CustomerType>Residential.*?</Customer>匹配整个记录住宅客户记录,但是我只想匹配客户记录中的CreditRating标签,以便进行搜索并更换。

Thanks a lot, 非常感谢,

:-) :-)

This is easy (and safe) in XSLT... 在XSLT中这很容易(也很安全)...

XML Input (wrapped in <Customers> to be well-formed) XML输入 (包装在<Customers> ,格式正确)

<Customers>
    <Customer>
        <CustomerType>Business</CustomerType>
        <CreditRating>Good</CreditRating>
    </Customer>
    <Customer>
        <CustomerType>Residential</CustomerType>
        <CreditRating>Good</CreditRating>
    </Customer>
</Customers>

XSLT 1.0 XSLT 1.0

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

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

    <xsl:template match="Customer[CustomerType='Residential']/CreditRating">
        <CreditRating>Bad</CreditRating>
    </xsl:template>

</xsl:stylesheet>

Output XML 输出XML

<Customers>
   <Customer>
      <CustomerType>Business</CustomerType>
      <CreditRating>Good</CreditRating>
   </Customer>
   <Customer>
      <CustomerType>Residential</CustomerType>
      <CreditRating>Bad</CreditRating>
   </Customer>
</Customers>

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

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