Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check particular attributes exist or not in XML?

Tags:

c#

xml

Part of the XML content:

<section name="Header">   <placeholder name="HeaderPane"></placeholder> </section>  <section name="Middle" split="20">   <placeholder name="ContentLeft" ></placeholder>   <placeholder name="ContentMiddle"></placeholder>   <placeholder name="ContentRight"></placeholder> </section>  <section name="Bottom">   <placeholder name="BottomPane"></placeholder> </section> 

I want to check in each node and if attribute split exist, try to assign an attribute value in a variable.

Inside a loop, I try:

foreach (XmlNode xNode in nodeListName) {     if(xNode.ParentNode.Attributes["split"].Value != "")     {         parentSplit = xNode.ParentNode.Attributes["split"].Value;     } } 

But I'm wrong if the condition checks only the value, not the existence of attributes. How should I check for the existence of attributes?

like image 722
4b0 Avatar asked Aug 25 '11 07:08

4b0


People also ask

How do I check if an element exists in XML?

How to check if xml node exists? To verify if node or tag exists in XML content, you can execute an xpath expression against DOM document for that XML and count the matching nodes. matching nodes > zero – XML tag / attribute exists. matching nodes <= zero – XML tag / attribute does not exist.

How many attributes are there in XML?

Attribute Types: There are three types of attributes described below: String types Attribute: This type of attribute takes any string literal as a value.

Does XML have attributes?

XML elements can have attributes, just like HTML. Attributes are designed to contain data related to a specific element.


1 Answers

You can actually index directly into the Attributes collection (if you are using C# not VB):

foreach (XmlNode xNode in nodeListName) {   XmlNode parent = xNode.ParentNode;   if (parent.Attributes != null      && parent.Attributes["split"] != null)   {      parentSplit = parent.Attributes["split"].Value;   } } 
like image 81
Paul Avatar answered Sep 22 '22 09:09

Paul