How To Parse XML In .NET Core
Please Subscribe Youtube| Like Facebook | Follow Twitter
In this tip, we will learn how to parse XML in .NET Core. We will use XmlDocument class which come under the System.Xml namespace.
Parsing XML
For example we have the following string of XML:
<ArrayPRODUCT>
<PRODUCT><PROD_CODE> 001 </PROD_CODE><PROD_NAME> PRODUCT1 </PROD_NAME></PRODUCT>
<PRODUCT><PROD_CODE> 002 </PROD_CODE><PROD_NAME> PRODUCT2 </PROD_NAME></PRODUCT>
<PRODUCT><PROD_CODE> 003 </PROD_CODE><PROD_NAME> PRODUCT3 </PROD_NAME></PRODUCT>
</ArrayPRODUCT>
First we will create object of XMLDocument class then we will load string of XML using created object. After loading string of XML we will get PRODUCT element by using GetElementsByTagName method of XMLDocument object. In last we will go through PRODUCT element using foreach loop and print PROD_CODE and PROD_NAME element inner text.
string xml = "<ArrayPRODUCT><PRODUCT><PROD_CODE> 001 </PROD_CODE><PROD_NAME> PRODUCT1 </PROD_NAME></PRODUCT> <PRODUCT><PROD_CODE> 002 </PROD_CODE><PROD_NAME> PRODUCT2 </PROD_NAME></PRODUCT><PRODUCT><PROD_CODE> 003 </PROD_CODE><PROD_NAME> PRODUCT3 </PROD_NAME></PRODUCT></ArrayPRODUCT>";
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xml);
var product = xDoc.GetElementsByTagName("PRODUCT");
XmlDocument xDocC = new XmlDocument();
foreach (XmlElement item in product)
{
Console.Write("Prod Code:" + item.GetElementsByTagName("PROD_CODE")[0].InnerText);
Console.WriteLine("Prod Name:" + item.GetElementsByTagName("PROD_NAME")[0].InnerText);
}
Please Subscribe Youtube| Like Facebook | Follow Twitter