我正忙于创建一个
XDocument
对象。在其中一个元素中,我需要添加域名和服务帐户。 服务帐户的形式如下:
MyDomainName\\MyServiceAccount
我需要标签看起来像:
<ChangeRunAsName>MyDomainName\MyServiceAccount</ChangeRunAsName>
无论我如何尝试用
\\
替换 \
,它仍然显示为 \\
。
这是我目前拥有的:
XDocument xDocument = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("MyAppsTable",
myApplications.Select(component => new XElement("MyApps",
new XElement("ChangeResult", string.Empty),
new XElement("ChangeRunAsName", serviceAccount.DomainServiceAccount.Replace("\\\\", "\\")
))
)
);
myApplications 和 serviceAccount 输入参数如下所示:
IEnumerable<MyApplication> myApplications
ServiceAccount serviceAccount
我尝试过以下方法:
serviceAccount.DomainServiceAccount.Replace("\\\\", "\\")
serviceAccount.DomainServiceAccount.Replace(@"\\", @"\")
...结果仍然是:
<ChangeRunAsName>MyDomainName\\MyServiceAccount</ChangeRunAsName>
我不知道该怎么办了。
我在上面的代码之后有这个:
string xml = xDocument.ToString();
调试时,我查看 xml 的内容,然后看到
\
和 \\
。 我需要将此 xml 字符串传递给另一个方法。
您正确替换了反斜杠。
但是,当您在 Visual Studio 调试器中查看结果时,它会转义反斜杠(添加额外的反斜杠),这给您一种它不起作用的印象。
要在调试器中查看实际字符串,您必须使用“文本可视化工具”。
要从“自动和本地”显示中执行此操作:仔细观察显示字符串的右侧,您会看到一个小放大镜。选择旁边的小下拉箭头,然后单击“文本可视化工具”。这将显示文本不带额外的反斜杠。
如果您从 Quickwatch 查看变量(右键单击变量并选择“Quickwatch”),也可以执行此操作。将会出现相同的小放大镜图标,旁边有一个下拉箭头,您可以单击下拉箭头并选择“文本可视化工具”。
我准备了以下示例。请将您的代码的调试值与我提供的代码进行比较。默认情况下,域名以 XML 格式保存,如您所希望的 “域\用户名” 格式。
XDocument xdoc = new XDocument();
xdoc.Add(new XElement("user",System.Security.Principal.WindowsIdentity.GetCurrent().Name));
xdoc.Save(@"d:\test.xml",SaveOptions.None);
我认为问题在于 DomainServiceAccount 是如何实现的。因为您没有发布此详细信息,所以我做了一些假设并定义了缺失的类,如下
class MyApplication { public ServiceAccount component { get; set; } }
class ServiceAccount { public string DomainServiceAccount { get; set; } }
然后我在 LinqPad 中创建了以下代码:
static void Main()
{
IEnumerable<MyApplication> myApplications=
new System.Collections.Generic.List<MyApplication>();
ServiceAccount serviceAccount=new ServiceAccount();
serviceAccount.DomainServiceAccount=@"test\\account";
((List<MyApplication>)myApplications).Add(new MyApplication() {
component=serviceAccount });
XDocument xDocument = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement("MyAppsTable",
myApplications.Select(component => new XElement("MyApps",
new XElement("ChangeResult", string.Empty),
new XElement("ChangeRunAsName",
serviceAccount.DomainServiceAccount.Replace("\\\\", "\\"))
)
)
)
);
xDocument.Dump();
}
这会产生以下输出:
<MyAppsTable>
<MyApps>
<ChangeResult></ChangeResult>
<ChangeRunAsName>test\account</ChangeRunAsName>
</MyApps>
</MyAppsTable>
如您所见,只有一个
\
,您需要拥有它。您可以在这里找到 LinqPad:下载链接(如果您想在我使用过的相同环境中尝试一下,在 LinqPad 中尝试代码片段通常比在 Visual Studio 中更快,因为您不需要首先创建一个项目)。
更新:我也用Visual Studio 2010 Ultimate进行了尝试,看看是否有任何差异。所以我创建了一个控制台应用程序,将
xDocument.Dump();
语句替换为
string xml = xDocument.ToString();
并在那里创建了一个断点 - 就像你所做的那样。当遇到断点时,我在 XML 可视化工具中查看了 xml 字符串,并得到了与 LinqPad 中相同的结果(如上所示)。文本可视化工具显示了相同的结果(只有一个反斜杠)。