In this article, I will explain how to use XDocument to read XML Attribute value.
Step 1: Add a TextBox and Button, TextBox will be used to search the attribute value based on the Id entered in the textbox.
<asp:TextBox ID="txtId" runat="server"></asp:TextBox>
<asp:Button ID="btnGetValue" Text="Get Value" runat="server" OnClick="btnGetValue_Click" />
Step 2: Create a XML file like below structure.
<Messages>
<Message id='One'>
<Display>Messageid is one.</Display>
</Message>
<Message id='Two'>
<Display>Messageid is two.</Display>
</Message>
<Message id='Three'>
<Display>Messageid is three.</Display>
</Message>
<Message id='Four'>
<Display>Messageid is four.</Display>
</Message>
<Message id='Four'>
<Display>Messageid is again four.</Display>
</Message>
<Message id='One'>
<Display>Messageid is again one.</Display>
</Message>
</Messages>
Step 3: Create a method GetValues which will return List of matching elements found in the XML document.
public static List<string> GetValues(string strFileName, string strDescendants, string strAttribute, string strAttributeValue, string strElement)
{
XDocument xmlDoc = XDocument.Load(strFileName); //Open XML file
var xmlValue = from c in xmlDoc.Descendants(strDescendants)
where c.Attribute(strAttribute).Value.ToLower().Equals(strAttributeValue.ToLower())
select (string)c.Element(strElement);
List<string> strList = xmlValue.ToList<string>();
return strList;
}
Step 4: btnGetValue_Click event of button will invoke GetValues
protected void btnGetValue_Click(object sender, EventArgs e)
{
string strFileName = Server.MapPath("Message.xml");
string strDescendants = "Message";
string strAttribute = "id";
string strAttributeValue = txtId.Text;
string strElement = "Display";
List<string> lstValues = GetValues(strFileName, strDescendants, strAttribute, strAttributeValue, strElement);
if (lstValues.Count > 0)
{
foreach (string strValue in lstValues)
{
Response.Write(strValue + "<br/>");
}
}
else
{
Response.Write("No matching record found.");
}
}
Visit LINQ - How to read and search an element in XML for live demo and download the code
No comments:
Post a Comment