从 XML 标签中提取键值 C# LINQ
Extracting Key value from XML tags C# LINQ
void Main()
{
string xml = @"<root>
<Page1>
<Key_Head>Name1</Key_Head>
<Key_Title>value1</Key_Title>
</Page1>
<Page1>
<Key_Head>Name2</Key_Head>
<Key_Title>value2</Key_Title>
</Page1>
</root>";
var doc1 = XDocument.Parse(xml);
var result = ConvertXmlToDic(doc1.Root);
}
private static List<NameValuePair> ConvertXmlToDic(XElement element)
{
var result =
element
.Elements()
.Select(e => new
{
Name = e.Name.ToString(),
Value = (e.Descendants().Count() == 0)
? e.Value
: ConvertXmlToDic(e).ToString()
})
.ToDictionary(e => e.Name, e => e.Value)
.Select(e => new List<NameValuePair>()
{
new NameValuePair() { Name = e.Key, Value = e.Value }
});
return (List<NameValuePair>)result;
}
如何获取 Name1 [=14= 的标签值]value1 作为键值。喜欢 (Name1,Value1) 的列表?这是我到目前为止尝试过的。
您可以简化检索 Key_Head
和 Key_Title
的逻辑,如下所示:
private static List<NameValuePair> ConvertXmlToDic(XElement element)
{
var result = element.Elements()
.Select(e => new NameValuePair
{
Name = e.Element("Key_Head").Value,
Value = e.Element("Key_Title").Value
})
.ToList();
return result;
}
Output
Name: Name1, Value: value1
Name: name2, Value: value2
void Main()
{
string xml = @"<root>
<Page1>
<Key_Head>Name1</Key_Head>
<Key_Title>value1</Key_Title>
</Page1>
<Page1>
<Key_Head>Name2</Key_Head>
<Key_Title>value2</Key_Title>
</Page1>
</root>";
var doc1 = XDocument.Parse(xml);
var result = ConvertXmlToDic(doc1.Root);
}
private static List<NameValuePair> ConvertXmlToDic(XElement element)
{
var result =
element
.Elements()
.Select(e => new
{
Name = e.Name.ToString(),
Value = (e.Descendants().Count() == 0)
? e.Value
: ConvertXmlToDic(e).ToString()
})
.ToDictionary(e => e.Name, e => e.Value)
.Select(e => new List<NameValuePair>()
{
new NameValuePair() { Name = e.Key, Value = e.Value }
});
return (List<NameValuePair>)result;
}
如何获取
您可以简化检索 Key_Head
和 Key_Title
的逻辑,如下所示:
private static List<NameValuePair> ConvertXmlToDic(XElement element)
{
var result = element.Elements()
.Select(e => new NameValuePair
{
Name = e.Element("Key_Head").Value,
Value = e.Element("Key_Title").Value
})
.ToList();
return result;
}
Output
Name: Name1, Value: value1
Name: name2, Value: value2