0

XML dataに基づいて値を読み取って取得していますelement<UniqueColumns>という名前の子要素を持つことができるという名前の要素が 1 つあり<string>ます。これらの値を読み取り、に追加したいと思いますObservableCollection<String>。値がない場合は、何もしません。次の 3 つのシナリオがあります。

シナリオ - 1: 複数の子要素。

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

シナリオ - 2: 子要素が 1 つだけ。

<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 に答える