【问题标题】:string.Replace symbols字符串。替换符号
【发布时间】:2015-05-07 16:36:34
【问题描述】:

我想替换 fetchxml 查询中的一些符号

Fetchxml.Replace("\"", "'").Replace("\n", "\"+").Replace("

我想用“+”替换\n(返回该行) 并将

示例 XML:

<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="account"> <attribute name="name" /> <filter type="and"> <condition attribute="statecode" operator="eq" value="0" /> </filter> <link-entity name="contact" from="contactid" to="primarycontactid" visible="false" link-type="outer" alias="accountprimarycontactidcontactcontactid"> <attribute name="emailaddress1" /> </link-entity> </entity> </fetch>

期望的输出:

<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"+ "<entity name='account'>"+ "<filter type='and'>"+ "<condition attribute='statecode' operator='eq' value='0' />"+ "</filter>"+ "</entity>"+ "</fetch>

【问题讨论】:

  • 请举例说明您的 XML 的样子,尤其是之前和之后的样子。 “替换”可能不是一个好的选择,因为 XML 不能那样工作。
  • 好吧,我的 fetchxml 就是这样 Fetxml = "获取>";
  • 在我希望它像那样之后,在我希望它像那样之后:Fetchxml=“"+ ""+ ""+ ""+ ""+ ""+ "";
  • 好的,你想用那个输出来完成什么?因为那看起来不再像 XML 了? (我已将您的 XML 编辑到问题中 - 我没有触及格式 - 您可能需要检查它,因为它可能很重要)。

标签: c# xml replace fetchxml


【解决方案1】:

看起来您要做的只是将“+”插入此 XML 的文本元素中。这有点奇怪,但我会咬一口的。

我建议这在 Perl 中很容易,使用 XML::Twig。 XML 的问题在于它不能用正则表达式轻松解析,但它确实 可以用 XML 解析器轻松解析。

所以给定的输入 XML 为:

<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0">
  <entity name="account">
    <attribute name="name"/>
    <filter type="and">
      <condition attribute="statecode" operator="eq" value="0"/>
    </filter>
    <link-entity alias="accountprimarycontactidcontactcontactid" from="contactid" link-type="outer" name="contact" to="primarycontactid" visible="false">
      <attribute name="emailaddress1"/>
    </link-entity>
  </entity>
</fetch>

它可以变成你想要的输出 XML的近似值:

#!/usr/bin/perl
use strict;
use warnings; 
my $xml = XML::Twig->new(
    'pretty_print'  => 'indented',
    'twig_handlers' => {
        'attribute'   => sub { $_->delete },
        'link-entity' => sub { $_->delete },
    },
);
$xml->parse( \*DATA );
$xml ->print;

这给了你:

<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0">
  <entity name="account">
    <filter type="and">
      <condition attribute="statecode" operator="eq" value="0"/>
    </filter>
  </entity>
</fetch>

(如果您不希望它行分隔和缩进,请关闭 pretty_print 标志) 现在,我不完全确定您要使用那里的 + 符号来完成什么。您是否试图引用您的 XML 结果?老实说,从 XML 的角度来看,这并没有多大意义。

如果你真的不得不这样做,我想你可以:

my $output_xml = $xml ->sprint;
$output_xml =~ s/^\s+//gm;
$output_xml =~ s/\n</"+ "</g;
print $output_xml;

这会给你:

<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0">"+ "<entity name="account">"+ "<filter type="and">"+ "<condition attribute="statecode" operator="eq" value="0"/>"+ "</filter>"+ "</entity>"+ "</fetch>

【讨论】:

  • 感谢您的回复,但我想用 c# 转换它,因为当我输入我的 fetchxml 查询时,在代码中重新添加到行中,所以我必须将 (\n) 替换为 "+
  • 如果你真的用语言标记你的问题,你会得到更好的语言特定答案。