1

我有以下xml:

<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可变的。

4

1 回答 1

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;
于 2012-05-14T12:16:26.387 回答