2012-05-14 68 views
1

我有以下XML:LinqToXml:解析和格式化

<Places Count='50'> 
<Place ID='1' Row='1' Place='1' Status='10' Fragment='0'></Place> 
<Place ID='2' Row='1' Place='2' Status='10' Fragment='0'></Place> 
<Place ID='3' Row='1' Place='3' Status='10' Fragment='0'></Place> 
<Place ID='4' Row='1' Place='4' Status='10' Fragment='0'></Place> 
//other tags 
</Places> 

这是我的方法:

public static List<string> ParseFreePlace(string response, string level) 
{ 
    if (string.IsNullOrWhiteSpace(response)) return new List<string>(); 

    return XDocument.Parse(response).Descendants("Place") 
     .Select(element => (string) element.Attribute("Row")).ToList(); 
} 

我想List<string>包含以下内容:

r=1;p=1;f=0;l=54; // 0 element in the List 
r=1;p=2;f=0;l=54; // 1 element in the List 
r=1;p=3;f=0;l=54; // 2 element in the List 
r=1;p=4;f=0;l=54; // 3 element in the List 

l的内容是level变量。

谢谢。

回答

2

试试这个:

public static List<string> ParseFreePlace(string response, string level) 
{ 
    if (string.IsNullOrWhiteSpace(response)) return new List<string>(); 

    return 
     XDocument.Parse(response) 
       .Descendants("Place") 
       .Select(e => 
        String.Format("r={0};p={1};f={2};l={3};", 
            e.Attribute("Row").Value, 
            e.Attribute("Place").Value, 
            e.Attribute("Fragment").Value, 
            level) 
       ).ToList(); 
} 

当这样调用(假设input是XML字符串):

var lines = ParseFreePlace(input, "54"); 
foreach (var line in lines) Console.WriteLine(line); 

它返回这对我来说:

r=1;p=1;f=0;l=54; 
r=1;p=2;f=0;l=54; 
r=1;p=3;f=0;l=54; 
r=1;p=4;f=0;l=54; 
+0

+1你已经忘记了后面的分号,但除此之外看起来不错。 – dasblinkenlight

+0

谢谢,也加了。 – yamen

+0

它仍然从示例输出中丢失:) – dasblinkenlight