Reputation: 253
i have an xml file:
<Address>
<Data2>
<Person>
<EMPL_NUM>>100</EMPL_NUM>
<NAME>Carl</NAME>
<ID_NUM>1</ID_NUM>
<IsRequired>0</IsRequired>
</Person>
<Person>
<EMPL_NUM>200</EMPL_NUM>
<NAME>Mark</NAME>
<ID_NUM>2</ID_NUM>
<IsRequired>0</IsRequired>
</Person>
<Person>
<EMPL_NUM>300</EMPL_NUM>
<NAME>Tanner</NAME>
<ID_NUM>3</ID_NUM>
<IsRequired>0</IsRequired>
</Person>
</Data2>
</Address>
I have a textbox and a button. When I type "1" and press the button my problem is how can i display the xml data to a datagridview where the value of the textbox would only show the data that has ID_num = textbox.text
expected output to datagrid:
if txtbox1.text = 1:
EMPL_NUM | Name | ID_NUM | IsRequired
100 | Carl | 1 | 0
if txtbox1.text = 3:
EMPL_NUM | Name | ID_NUM | IsRequired
300 | Tanner | 3 | 0
Upvotes: 1
Views: 46
Reputation: 9829
try this:
class Program
{
static void Main(string[] args)
{
// read your xml from somewhere
var xml = File.ReadAllText("Address.xml");
XDocument xmldoc = XDocument.Parse(xml);
// get the element by id
var element = GetElementById(xmldoc, 1);
// deserialize element
var xmlSerializer = new XmlSerializer(typeof(Person));
var person = (Person)xmlSerializer.Deserialize(element.CreateReader());
// continue to work with person
}
private static XElement GetElementById(XDocument xmldoc, string id)
{
// Elements according to your XML file
var element = xmldoc.Element("Address")
.Elements("Data2")
.Elements("Person")
.Single(x => x.Element("ID_NUM").Value == id);
return element;
}
}
/// <summary>
/// Used for deserialization
/// </summary>
public class Person
{
public int EMPL_NUM { get; set; }
public string NAME { get; set; }
public int ID_NUM { get; set; }
public bool IsRequired { get; set; }
}
Upvotes: 3