I'm kinda new with using XML with C#.
XML CODE:
<LVL2>
<Tables>
<TBL_ID>1</TBL_ID>
<TBL_Name>test1</TBL_Name>
<MD_ID>1</MD_ID>
<Tables>
<Tables>
<TBL_ID>2</TBL_ID>
<TBL_Name>test2</TBL_Name>
<MD_ID>1</MD_ID>
</Tables>
<Tables>
<TBL_ID>3</TBL_ID>
<TBL_Name>test3</TBL_Name>
<MD_ID>1</MD_ID>
</Tables>
</LVL2>
<LVL2>
<Tables>
<TBL_ID>1</TBL_ID>
<TBL_Name>test4</TBL_Name>
<MD_ID>2</MD_ID>
</Tables>
<Tables>
<TBL_ID>2</TBL_ID>
<TBL_Name>test5</TBL_Name>
<MD_ID>2</MD_ID>
</Tables>
<Tables>
<TBL_ID>3</TBL_ID>
<TBL_Name>test6</TBL_Name>
<MD_ID>2</MD_ID>
</Tables>
</LVL2>
How do I insert to a checkedlistbox the text values from tbl_name
that has an md_id = 1
only. Here is my current code.
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
elName = xmlReader.Name;
break;
case XmlNodeType.Text:
if (elName == "TBL_Name" && MD_ID == "1")
{
checkedListBox2.Items.Add(xmlReader.Value);
}
break;
}
}
I can't seem to figure out on how to get the text that has MD_ID = "1"
and output:
test4
test5
test6
First of all, the xml is not formatted properly. It should contain a root node and you missed the closing of a <Tables>
tag. In the sample example, if you want to choose table names of elements having "MD_ID = 1" , the result will be:
test1
test2
test3
If you want o/p as you mentioned, then the condition will be not equal to 1. Here is the solution:
string xmlInput = @"
<root>
<LVL2>
<Tables>
<TBL_ID>1</TBL_ID>
<TBL_Name>test1</TBL_Name>
<MD_ID>1</MD_ID>
</Tables>
<Tables>
<TBL_ID>2</TBL_ID>
<TBL_Name>test2</TBL_Name>
<MD_ID>1</MD_ID>
</Tables>
<Tables>
<TBL_ID>3</TBL_ID>
<TBL_Name>test3</TBL_Name>
<MD_ID>1</MD_ID>
</Tables>
</LVL2>
<LVL2>
<Tables>
<TBL_ID>1</TBL_ID>
<TBL_Name>test4</TBL_Name>
<MD_ID>2</MD_ID>
</Tables>
<Tables>
<TBL_ID>2</TBL_ID>
<TBL_Name>test5</TBL_Name>
<MD_ID>2</MD_ID>
</Tables>
<Tables>
<TBL_ID>3</TBL_ID>
<TBL_Name>test6</TBL_Name>
<MD_ID>2</MD_ID>
</Tables>
</LVL2>
</root>";
XDocument xdoc = XDocument.Parse(xmlInput);
var filteredXML =
xdoc.Descendants("root")
.Elements("LVL2")
.Elements("Tables")
.Where(x => string.Compare(x.Element("MD_ID").Value, "1") == 0)
.Select(x => x.Element("TBL_Name").Value)
.ToList();
Console.WriteLine(filteredXML);
Refer following namespace:
using System.Xml.Linq;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.