Reputation: 97
<tags>
<data mode="add" name="ttt" oldindex="-1" index="-1" oldnumber="1" number="1" type="VAR_INT" value="72" />
<data mode="delete" name="test3d" oldindex="-1" index="-1" oldnumber="1" number="1" type="VAR_INT" value="72" />
</tags>
I want to check whether "mode" is present in xml or not
xdDiffData.XPathSelectElement("//tags[@mode='add']") != null && xdDiffData.XPathSelectElement("//tags[@mode='delete']") != null
This always gives false..how to do this... ?
Upvotes: 1
Views: 573
Reputation: 243459
I want to check whether "mode" is present in xml or not
Use:
//@mode
if this XPath expression selects a node, this means that an attribute named mode
is present in the XML document.
or you could use:
boolean(//@mode)
and this produces a boolean value -- true()
or false()
Upvotes: 0
Reputation: 16698
If you want to make sure that mode
attribute is present in every data
element, then you should better iterate all the data elements to look for the mode
attribute this way:
XDocument doc = XDocument.Load("XmlFile.xml");
var nodes = doc.Descendants("data");
foreach (var node in nodes)
{
var attrMode = node.Attribute("mode");
if (attrMode == null)
{
// mode attribute is not available for this data element
}
}
Using Linq:
if (nodes.Where(c => c.Attribute("mode") == null).Count() == 0)
{
var result = nodes.All(e =>
e.Attribute("mode").Value.Equals("add") ||
e.Attribute("mode").Value.Equals("delete"));
}
else
{
// 'mode' attribute is missing for one or more 'data' element(s)
}
If result
equals to true
, then it means all the data elements have mode
attribute either set to value "add"
or "delete"
.
Upvotes: 2
Reputation: 97
xdDiffData.XPathSelectElement("/tags/data[@mode='add']") != null
Upvotes: 0
Reputation: 2322
You are missing the 'data' element. Try
xdDiffData.XPathSelectElement("//tags/data[@mode='add']") != null && xdDiffData.XPathSelectElement("//tags/data[@mode='delete']") != null
Upvotes: 0