In C#, How would you return a value from an XML file? First input from user: Con
ID: 3802595 • Letter: I
Question
In C#, How would you return a value from an XML file?
First input from user:
Console.Write("Enter Word to be Determined: ");
string Word = Console.ReadLine();
sw.WriteLine(Word);
if (Word == "")
break;
Console.WriteLine(sr.ReadLine());
It then prints out the file that is written in the XML file.
How would you get Another file? An example key of XML "1001" its value is "HAT"
then "HAT" relates to another Key in the XML file with the value of "52"
it then prints out all of it.
Explanation / Answer
It is easy...
Steps to answer this solution..
1) First read input from user
2) open first xml and fetch the resuls matching with user input
3) Using for loop , iterate all keys and then open second xml and print the matched results.
Here is the code..
//sample first xml
<data>
<1001>HAT</1001>
</data>
//second xml
<data>
<HAT>Hello World</HAT>
</data>
PROGRAM CODE
using System;
using System.Xml;
using System.IO;
namespace MyPrograms
{
class ParseXML
{
void WriteLine(string word){
//parsing xml
XDocument myxmldoc = XDocument.Load("first.xml");
var nodes = myxmldoc.Descendants("1001")
.Select(x => new { Execution = x.Attribute("value").Value});
foreach (var node in nodes)
{
//parsing second xml
XDocument myxmldoc2 = XDocument.Load("second.xml");
var nodes2 = myxmldoc2.Descendants(node)
.Select(x => new { Execution = x.Attribute("value").Value});
foreach (var node2 in nodes2)
{
Console.WriteLine("Value = {0}", node2.value);
}
}
}
static void Main(string[] args)
{
Console.Write("Enter Word to be Determined: ");
string Word = Console.ReadLine();
ParseXML sw = new ParseXML();
sw.WriteLine(Word);
if (Word == "")
break;
Console.WriteLine(sw.ReadLine());
}
}
}
Note: Before running this program, check your IDE should import Using System.Xml to work with XmlDocument.