如何在C#中将XML转换为字符串格式 [英] How to convert XML to string format in C#
本文介绍了如何在C#中将XML转换为字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< language>
< record lang =。net>
< record lang =java>
< record lang =php>
i想要输出字符串temp =。net,java, php
我的尝试:
< language>
< record lang =。net>
< record lang =java>
< record lang = php>
i想要输出字符串temp =。net,java,php。我试图绑定它,但不能来。任何人都可以帮助我。
<language>
<record lang=".net">
<record lang="java">
<record lang="php">
i want to the ouput on string temp=".net,java,php"
What I have tried:
<language>
<record lang=".net">
<record lang="java">
<record lang="php">
i want to the ouput on string temp=".net,java,php". i tried to bind it, but not able to come. can anyone pls help me.
推荐答案
该XML无效,因为没有结束标记,但假设您的实际XML有效,您可以这样做:
That XML isn't valid because there are no closing tags, but assuming your actual XML is valid, you can do this:
using System.Xml.Linq;
string xml = @"<language>
<record lang="".net""></record>
<record lang=""java""></record>
<record lang=""php""></record>
</language>";
string temp = string.Join(",", XDocument.Parse(xml).Root.Elements().Select(x => x.Attribute(XName.Get("lang")).Value));
- XDocument.Parse将您的字符串解析为
XDocument
-
.Root
获取根元素,< language>
- .Elements()接受子元素,三个
< record>
-tags。 -
.Select(x => x.Attribute(XName.Get(lang))。Value)
获取每个元素的lang属性的值。结果是IEnumerable< string>
。
-
string.Join
连接这些字符串,逗号作为分隔符。 - XDocument.Parse parses your string into an
XDocument
.Root
takes the root element,<language>
- .Elements() takes the child elements, the three
<record>
-tags. .Select(x => x.Attribute(XName.Get("lang")).Value)
takes the value of the "lang" attribute for each of these elements. The result is anIEnumerable<string>
.
string.Join
concatenates these strings, with a comma as separator.
这篇关于如何在C#中将XML转换为字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文