C# 将 XElement 转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1942530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:03:57  来源:igfitidea点击:

Convert XElement to string

c#xmllinqlinq-to-xml

提问by

I have a simple XElement object

我有一个简单的 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")
);

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.

要将内容转储到字符串中的位置。就像怎么Console.Writeline(xml);做一样,但我想要字符串中的内容。我尝试了各种方法。xml.ToString();不会自行返回任何内容。

采纳答案by Patrick Karcher

ToStringshould most definately 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 your XElement. To debug, rewrite the code to add each of the child XElements 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.

ToString应该绝对有效。我用它所有的时间。在这种情况下,它会给你带来什么回报?空字符串?我的猜测是构建您的XElement. 要进行调试,请重写代码以分别添加每个 child XElement,以便您可以单步执行代码并检查它们中的每一个。然后在执行之前.ToString,在 Locals 窗口中,查看[xml]扩展为 xml的变量。

In short, your problem is happening before you ever get to the ToString()method.

简而言之,您的问题在您使用该ToString()方法之前就已经发生了。

回答by Mike Keskinov

ToStringworks, but it returns content including XElement tag itself. If you need for Inner XMLwithout root tag ("" in your example), you may use the following extension method:

ToString有效,但它返回包括 XElement 标签本身的内容。如果您需要没有根标记的内部 XML(在您的示例中为“”),您可以使用以下扩展方法:

public static class XElementExtension
{
    public static string InnerXML(this XElement el) {
        var reader = el.CreateReader();
        reader.MoveToContent();
        return reader.ReadInnerXml();
    }
}

Then simple call it: xml.InnerXML();

然后简单地调用它: xml.InnerXML();