使用C#普通EX pression替换XML元素内容 [英] Using C# Regular expression to replace XML element content

查看:192
本文介绍了使用C#普通EX pression替换XML元素内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一些code处理记录XML数据,我想能够替换文档中的某些元素(如密码)的内容。我宁愿不序列化和解析为我的code将处理各种架构的文档。

I'm writing some code that handles logging xml data and I would like to be able to replace the content of certain elements (eg passwords) in the document. I'd rather not serialize and parse the document as my code will be handling a variety of schemas.

样品输入文档:

DOC#1:

   <user>
       <userid>jsmith</userid>
       <password>myPword</password>
    </user>

DOC#2:

doc #2:

<secinfo>
       <ns:username>jsmith</ns:username>
       <ns:password>myPword</ns:password>
 </secinfo>

我想我的输出是:

What I'd like my output to be:

输出文档#1:

<user>
       <userid>jsmith</userid>
       <password>XXXXX</password>
 </user>

输出文档#2:

output doc #2:

<secinfo>
       <ns:username>jsmith</ns:username>
       <ns:password>XXXXX</ns:password>
 </secinfo>

由于文档,我会处理可以有多种模式,我希望拿出一个很好的通用常规EX pression解决方案,可以发现他们的密码内容,并相应地掩盖的内容。

Since the documents I'll be processing could have a variety of schemas, I was hoping to come up with a nice generic regular expression solution that could find elements with password in them and mask the content accordingly.

我可以解决这个问题用常规的前pressions和C#或者是有没有更有效的方法?

Can I solve this using regular expressions and C# or is there a more efficient way?

推荐答案

这个问题最好用XSLT解决:

This problem is best solved with XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@* | node()">
    	<xsl:copy>
    		<xsl:apply-templates select="@* | node()"/>
    	</xsl:copy>
    </xsl:template>
    <xsl:template match="//password">
    	<xsl:copy>
    		<xsl:text>XXXXX</xsl:text>
    	</xsl:copy>
    </xsl:template>
</xsl:stylesheet>

这将为两个输入,只要你正确地处理了名称空间的工作。

This will work for both inputs as long as you handle the namespaces properly.

确认已在 NS 名称preFIX已作为命名空间中定义的,像这样的文件的源文件:

Make sure your source document that has the ns name prefix has as namespace defined for the document like so:

<?xml version="1.0" encoding="utf-8"?>
<secinfo xmlns:ns="urn:foo">
    <ns:username>jsmith</ns:username>
    <ns:password>XXXXX</ns:password>
</secinfo>

这篇关于使用C#普通EX pression替换XML元素内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆