将 XElement 转换为字符串
我有一个简单的 XElement 对象
XElement xml = new XElement("XML",
new XElement ("TOKEN",Session["Token"]),
new XElement("ALL_INCLUSIVE", "0"),
new XElement("BEACH", "0"),
new XElement("DEST_DEP", ddlDest.SelectedValue.ToString()),
new XElement("FLEX", "0")
);
,想要将内容转储到字符串中。与 Console.Writeline(xml);
完全相同,但我想要字符串中的内容。我尝试了各种方法。 xml.ToString();
本身不返回任何内容。
I have a simple XElement object
XElement xml = new XElement("XML",
new XElement ("TOKEN",Session["Token"]),
new XElement("ALL_INCLUSIVE", "0"),
new XElement("BEACH", "0"),
new XElement("DEST_DEP", ddlDest.SelectedValue.ToString()),
new XElement("FLEX", "0")
);
Where want to dump out the contents into a string. Exactly like how Console.Writeline(xml);
does, but I want the contents in a string. I tried various methonds. xml.ToString();
doesn't return anything on its own.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ToString
绝对应该有效。我一直用它。在这种情况下,它会为您返回什么?空字符串?我的猜测是构建您的XElement
时出了问题。要进行调试,请重写代码以分别添加每个子XElement
,以便您可以单步执行代码并检查每个子XElement
。然后,在执行.ToString
之前,在 Locals 窗口中查看展开为 xml 的[xml]
变量。简而言之,您的问题是在您使用
ToString()
方法之前发生的。ToString
should most definitely work. I use it all the time. What does it return for you in this case? An empty string? My guess is that something went wrong building yourXElement
. To debug, rewrite the code to add each of the childXElement
s separately, so that you can step through your code and check on each of them. Then before you execute the.ToString
, in the Locals window, look at the[xml]
variable expanded to xml.In short, your problem is happening before you ever get to the
ToString()
method.ToString
有效,但它返回的内容包括 XElement 标记本身。如果您需要不带根标签(示例中为“”)的内部XML,您可以使用以下扩展方法:然后简单地调用它:
xml.InnerXML();
ToString
works, but it returns content including XElement tag itself. If you need for Inner XML without root tag ("" in your example), you may use the following extension method:Then simple call it:
xml.InnerXML();