使用C#普通EX pression替换XML元素内容元素、普通、内容、pression

2023-09-03 13:40:34 作者:一克拉的微笑

我在写一些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>