使用XmlTextReader读取元素中的元素
本文关键字:元素 读取 XmlTextReader 使用 | 更新日期: 2023-09-27 18:02:47
我正在读取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);
}