0

我正在读取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;
4

2 回答 2

1

使用 Linq2Xml 怎么样?

var xDoc = XDocument.Load(filename);
//var xDoc = XDocument.Parse(xmlstring);
var strings = xDoc.XPathSelectElements("//UniqueColumns/string")
                .Select(x => x.Value)
                .ToList();
于 2015-07-15T18:19:27.027 回答
0
//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);
        }
于 2015-07-15T18:48:08.107 回答