如何在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.