使用 XmlTextReader 读取元素中的元素

Read element within elements using XmlTextReader

我正在阅读 XML data 并根据 element 检索值。有一个名为 <UniqueColumns> 的元素可以有一个名为 <string> 的子元素。我想读取这些值并将其添加到 ObservableCollection<String>。如果没有价值,那么什么都不做。有以下三种情况:

场景 - 1:超过 1 个子元素。

<IndexId>4</IndexId>
<UniqueColumns>
  <string>Dir_nbr</string>
  <string>Dir_name</string>
</UniqueColumns>
<SelectedTableForUniqColumn>TBDirectory</SelectedTableForUniqColumn>

场景 - 2:只有一个子元素。

<IndexId>4</IndexId>
<UniqueColumns>
  <string>Dir_nbr</string>
</UniqueColumns>
<SelectedTableForUniqColumn>TBDirectory</SelectedTableForUniqColumn>

场景 - 3:没有子元素。

<IndexId>4</IndexId>
<UniqueColumns/>
<SelectedTableForUniqColumn>TBDirectory</SelectedTableForUniqColumn>

代码:

//This is a user defined data object and it has parameter which is type of `ObservableCollection<String>`. 
ExternalDatabaseTableRequestDO req = new ExternalDatabaseTableRequestDO();

using (XmlTextReader reader = new XmlTextReader(new StringReader(xmlData)))
{
    while (reader.Read())
    {
        int result;
        long res;
        string parameterValue;
        ObservableCollection<String> parameterValueList = new ObservableCollection<String>();

        switch (reader.Name.ToLower())
        {
            case "indexid":
                parameterValue = reader.ReadString();
                if (!String.IsNullOrWhiteSpace(parameterValue) && Int32.TryParse(parameterValue, out result))
                   req.IndexId = result;
                break;

            case "uniquecolumns":
                //need loop logic here but not sure how to do that.
                if (reader.NodeType == XmlNodeType.Element) // This will give me parent element which is <UniqueColumns>
                {
                    //Stuck here. How to read child elements if exists.
                }
                break;

            case "selectedtableforuniqcolumn":
                parameterValue = reader.ReadString();
                req.SelectedTableForUniqColumn = parameterValue;
                break;
        }
    }
}
return req;

使用 Linq2Xml 怎么样?

var xDoc = XDocument.Load(filename);
//var xDoc = XDocument.Parse(xmlstring);
var strings = xDoc.XPathSelectElements("//UniqueColumns/string")
                .Select(x => x.Value)
                .ToList();
//This will give me all child element values if they exists   
 var columnList = XElement.Parse(xmlData).Descendants("string").ToList();

        if (columnList != null)
        {
            foreach (var column in columnList)
                parameterValueList.Add(column.Value);
        }