I have this code: and i want to when i do the query to print one field in xml file.
I mean print only the field "Name"
How can i do that?
thanks
c#:
private void button1_Click(object sender, EventArgs e)
{
var name = textBox3.Text;
XDocument doc = XDocument.Load(@"data.xml");
var xpath = "//*[text()= ' " name "']";
var result = ((IEnumerable)doc.XPathEvaluate(xpath)).Cast<XElement>().FirstOrDefault();
var storeElement = doc.Descendants("store").Where(e => e.Attribute("rollNumer").Value == name).First();
textBox1.Text = storeElement.Value;
}
XML:
<?xml version="1.0" encoding="utf-8" ?>
<stores>
<store rollNumer="170">
<Name>Jonh</Name>
<Color>Pink</Color>
<Sell>Sugar</Sell>
</store>
<store rollNumer="120">
<Name>Tedy</Name>
<Color>Brown</Color>
<Sell>Rice</Sell>
</store>
</stores>
CodePudding user response:
Please try the following solution.
For your real scenario, just uncomment the .Load()
method, and comment out the .Parse()
method.
c#
void Main()
{
const string inputFile = @"e:\Temp\data.xml";
//XDocument xdoc = XDocument.Load(inputFile);
XDocument xdoc = XDocument.Parse(@"<stores>
<store rollNumer='170'>
<Name>Jonh</Name>
<Color>Pink</Color>
<Sell>Sugar</Sell>
</store>
<store rollNumer='120'>
<Name>Tedy</Name>
<Color>Brown</Color>
<Sell>Rice</Sell>
</store>
</stores>");
XElement helem = xdoc.Descendants("Name").FirstOrDefault();
string output = helem .Value;
}
CodePudding user response:
Hope will help you
XDocument doc = XDocument.Load(inputFile);
string storeElement = string.Empty;
foreach (var item in doc.Descendants("store"))
{
if (item.Attribute("rollNumer").Value == name)
{
storeElement = item.Descendants("Name").First().Value;
}
}