Check if any XML nodes exists with Specific Attribute using LINQ C# - c#

This is my XML:
<configuration>
<Script name="Test Script">
<arguments>
<argument key="CheckStats" value="True" />
<argument key="ReferenceTimepoint" value="SCREENING" />
<argument key="outputResultSetName" value="ResultSet" />
</arguments>
</Script>
</configuration>
I am trying to use this linq statement to grab an argument element's value attrbiute if a specific key attribute exists.
XElement root = XElement.Load(configFileName);
var AttrVal = from el in root.Elements("Script").Elements("arguments").Elements("argument")
where el.Attribute("key").Value == "CheckStats"
select el.Attribute("value").Value;
Then I want to try and parse the attribute value into a boolean:
bool checkVal;
if (AttrVal != null)
{
if (!bool.TryParse(AttrVal.First().ToString(), out checkVal))
{
throw new Exception(string.Format("Invalid value"));
}
}
This code works if there is an element with that attribute, but if there isn't one, I get a System.InvalidOperationException: Sequence contains no elements.
How can I get around that?
I thought by checking if (AttrVal != null) it would work.
Should I replace that with if (AttrVal.FirstOrDefault() != null) or something similar?
Thanks

In if statement, you can write
if (AttrVal != null && AttrVal.Any())
EDIT: I'm wrong. The exception should come from First(), not any of Elements(). Old answer:
from el in root.Descendants("argument")
Or
from el in root.XPathSelectElements("./Script/arguments/argument")

you have to check if there is already your attribute in the element where el.Attributes("key")!=null&&
XElement root = XElement.Load("config.xml");
var AttrVal = from el in root.Elements("Script").Elements("arguments").Elements("argument")
where el.Attributes("key")!=null&& el.Attribute("key").Value == "CheckStats"
select el.Attribute("value").Value;
bool checkVal;
if (AttrVal != null)
{
if (!bool.TryParse(AttrVal.First().ToString(), out checkVal))
{
throw new Exception(string.Format("Invalid value"));
}
}

Here's a way to eliminate those pesky null checks - seek ahead with XPath to determine whether a node with both the necessary attributes (viz key="CheckStats" AND a value) exists, then parse it.
bool checkVal;
// using System.Xml.XPath;!
var el = root.XPathSelectElement(
"/Script/arguments/argument[#key='CheckStats' and #value]");
if (el != null && !bool.TryParse(el.Attribute("value").Value,
out checkVal))
{
throw new Exception(string.Format("Invalid value"));
}

Related

XML Node Attribute returning as NULL when populated?

I have a XML Doc that I'm pulling out a specific Node and all of it's attributes. In debug mode I can see that I'm getting the specific Nodes and all of their attributes. However, when I try to get the attribute value it can't find it and returns a NULL value. I've done some searching and looked at some examples and from what I can tell I should be getting the value but I'm not and I don't see what I'm doing wrong.
I'm trying to get the StartTime value.
Here is the XML that is returned.
Here you can see in debug and with the Text Visualizer the value should be there.
The code I'm trying.
XmlNodeList nodes = xmlDoc.GetElementsByTagName("PlannedAbsences");
if (nodes != null && nodes.Count > 0)
{
foreach (XmlNode node in nodes)
{
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["StartTime"];
if (nameAttribute != null)
{
//var startDate = nameAttribute.Value;
}
}
}
}
Using the XDocument class contained within the System.Xml.Linq namespace, grab the sub elements from the PlannedAbsences parent, then iterate over sub elements retrieving the value of the desired attribute.
var xmlDoc = XDocument.Load(#"path to xml file")
var absences = xmlDoc.Element("PlannedAbsences")?.Elements("Absence");
foreach (var item in absences)
{
var xElement = item.Attribute("StartTime").Value;
Console.WriteLine(xElement);
}

c# "if" statement not working . Checking all variables are null

I have this XML file
<?xml version="1.0" encoding="utf-8"?>
<message>
<success/>
<bookings>
<booking>
<rooms>
<room roomCode ="101" uniqueId="abc">
<stays>
<stay usedfrom="9:30" usedto="10:30" quantity="1" Price="62.5" rateCode="1"/>
</stays>
<extras>
<extra from="9:30" to="10:30" unitPrice="5.5" extraCode="coffee" quantity="1" inclusive="0"/>
</extras>
<guests>
<guest firstName="John" lastName="Doe" title="MR" ageRange="0"/>
</guests>
</room>
<room roomCode ="Brd" uniqueId="xyz">
<stays>
<stay usedfrom="13:30" usedto="15:30" quantity="1" unitPrice="60.0000" rateCode="RACK"/>
</stays>
<guests>
<guest firstName="Jean" lastName="Doe" title="MRS" ageRange="0"/>
</guests>
</room>
</rooms>
</booking>
and i'm trying to run a check to make sure its in the correct format (ie certain elements are present).
The code I have been using is
XmlNodeList Successful = doc.GetElementsByTagName("success");
XmlNodeList Bookings = doc.GetElementsByTagName("bookings");
XmlNodeList Booking = doc.GetElementsByTagName("booking");
XmlNodeList Rooms = doc.GetElementsByTagName("rooms");
if ((Successful != null) && (Bookings != null) && (Booking != null) && (Rooms != null))
{
//do something
}
else
{
//do something else
}
This ALWAYS works thought.
If I change the one of the values to
XmlNodeList Rooms = doc.GetElementsByTagName("NoSuchElement");
(which does not exist in the XML) it still "works".
Can someone point out what I've done wrong (I've tried removing the outer brackets from the "if" statement, but this did not change the outcome).
Thanks
As opf the docs:
An XmlNodeList containing a list of all matching nodes. If no nodes
match name, the returned collection will be empty.
The method canĀ“t return null, but an empty list. So check for this instead:
if(theNodeList.Any()) { ... }
else { /* error */ }
This is because oc.GetElementsByTagName("NoSuchElement"); is never null.
As per the documentation, if no element exists, it returns en empty collection which is not null.
You have to check the Count of the result.
something like :
if (Successful.Count() != 0 && ...)
or
if (!Successful.Any() && ... )

Confused about linq this query

I have an xml file like this.
<Accounts>
<Account Id="">
<UserName/>
<Password/>
<AddingDate/>
<AccountType/>
</Account>
</Accounts>
What I want to do is that if the first element's attaribute value is not empty return true otherwise false
private bool IsListEmpty(){
XDocument doc = XDocument.Load("UserAccounts.xml");
var c = from p in doc.Descendants("Account")
where p.Element("Id").Value == ""
select p.Value;
if(c==null)return......
}
But I am stuck.How can I do this
Just use FirstOrDefault() on your LINQ and then check if Id attribute is empty:
var account = doc.Descendants("Account").FirstOrDefault();
return account != null && !string.IsNullOrEmpty(account.Attribute("Id").Value)
Not sure if I understand correctly but I think that .Any would do the trick.
XElement xelement = XElement.Load("UserAccounts.xml");
return xelement.Elements("Account").Where(x => string.IsNullOrEmpty((string)x.Element("Id"))).Any();
Any will return true if one element is found that is ""

Looking for performant XyDiff Port in C# (XML Diff Patch with XID)

I store some data as XML and the changes of the user as diff to the original XML, so the data for the user can be patched on runtime.
Example for the original xml (only part of it):
<module id="">
<title id="">
...
</title>
<actions>
...
</actions>
<zones id="" selected="right">
<zone id="" key="right" name="Right" />
</zones>
</module>
Example of the user diff (the user changed the value of selected from right to left):
<xd:xmldiff version="1.0" srcDocHash=""
options="IgnoreChildOrder IgnoreNamespaces IgnorePrefixes IgnoreSrcValidation "
fragments="no"
xmlns:xd="http://schemas.microsoft.com/xmltools/2002/xmldiff">
<xd:node match="1">
<xd:node match="3">
<xd:change match="#selected">left</xd:change>
</xd:node>
</xd:node>
</xd:xmldiff>
The problem is, that the patch looks for the order of the XML nodes. If the order changes than the diff cannot be applied anymore or even worse it will be applied wrongly. So I would prefer patching by XID.
Does anyone know a performant library or algorith for C# for a XyDiff?
We developed now our own solution that works fine.
What did we do:
ensure that every xml node in the original file has an unique id (no
matter on which level)
generate a flat xml patch for user changes that only saves the
changes of each changed node (without the level structure)
if the user changes a value, write a xmlpatch node in the patch xml
with attribute targetid pointing to the id of the original node
if the user changed an attribute, write the attribute with the new
value to the xmlpatch node
if the user changes a value, write the value to the xmlpatch node
The xml patch looks the following:
<patch>
<xmlpatch sortorder="10" visible="true" targetId="{Guid-x}" />
<xmlpatch selected="left" targetId="{Guid-y}" />
<xmlpatch targetId="{Guid-z}">true</xmlpatch>
</patch>
The code to produce the patch xml is pretty easy. We loop throug all xml nodes and for each node through all attributes. If an attribute or value of a node is different to the original, we generate the patch node with the attribute or value. Please note that the code was written in one night ;)
public static XDocument GenerateDiffGram(XDocument allUserDocument, XDocument runtimeDocument)
{
XDocument diffDocument = new XDocument();
XElement root = new XElement("patch");
AddElements(root, runtimeDocument, allUserDocument.Root);
diffDocument.Add(root);
return diffDocument;
}
private static void AddElements(XElement rootPatch, XDocument runtimeDocument, XElement allUserElement)
{
XElement patchElem = null;
if (allUserElement.Attribute("id") != null
&& !string.IsNullOrWhiteSpace(allUserElement.Attribute("id").Value))
{
// find runtime element by id
XElement runtimeElement = (from e in runtimeDocument.Descendants(allUserElement.Name)
where e.Attribute("id") != null
&& e.Attribute("id").Value.Equals(allUserElement.Attribute("id").Value)
select e).FirstOrDefault();
// create new patch node
patchElem = new XElement("xmlpatch");
// check for changed attributes
foreach (var allUserAttribute in allUserElement.Attributes())
{
XAttribute runtimeAttribute = runtimeElement.Attribute(allUserAttribute.Name);
if (!allUserAttribute.Value.Equals(runtimeAttribute.Value))
{
patchElem.SetAttributeValue(allUserAttribute.Name, runtimeAttribute.Value);
}
}
// check for changed value
if (!allUserElement.HasElements
&& !allUserElement.Value.Equals(runtimeElement.Value))
{
patchElem.Value = runtimeElement.Value;
}
}
// loop through all children to find changed values
foreach (var childElement in allUserElement.Elements())
{
AddElements(rootPatch, runtimeDocument, childElement);
}
// add node for changed value
if (patchElem != null
&& (patchElem.HasAttributes
|| !string.IsNullOrEmpty(patchElem.Value)))
{
patchElem.SetAttributeValue("targetId", allUserElement.Attribute("id").Value);
rootPatch.AddFirst(patchElem);
}
}
On runtime we patch the changes saved in the patch xml back. We geht the original node by the targetid and overwrite the attributes and values.
public static XDocument Patch(XDocument runtimeDocument, XDocument userDocument, string modulePath, string userName)
{
XDocument patchDocument = new XDocument(userDocument);
foreach (XElement element in patchDocument.Element("patch").Elements())
{
// get id of the element
string idAttribute = element.Attribute("targetId").Value;
// get element with id from allUserDocument
XElement sharedElement = (from e in runtimeDocument.Descendants()
where e.Attribute("id") != null
&& e.Attribute("id").Value.Equals(idAttribute)
select e).FirstOrDefault();
// element doesn't exist anymore. Maybe the admin has deleted the element
if (sharedElement == null)
{
// delete the element from the user patch
element.Remove();
}
else
{
// set attributes to user values
foreach (XAttribute attribute in element.Attributes())
{
if (!attribute.Name.LocalName.Equals("targetId"))
{
sharedElement.SetAttributeValue(attribute.Name, attribute.Value);
}
}
// set element value
if (!string.IsNullOrEmpty(element.Value))
{
sharedElement.Value = element.Value;
}
}
}
// user patch has changed (nodes deleted by the admin)
if (!patchDocument.ToString().Equals(userDocument.ToString()))
{
// save back the changed user patch
using (PersonalizationProvider provider = new PersonalizationProvider())
{
provider.SaveUserPersonalization(modulePath, userName, patchDocument);
}
}
return runtimeDocument;
}

How do I check particular attributes exist or not in 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?
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;
}
}
If your code is dealing with XmlElements objects (rather than XmlNodes) then there is the method XmlElement.HasAttribute(string name).
So if you are only looking for attributes on elements (which it looks like from the OP) then it may be more robust to cast as an element, check for null, and then use the HasAttribute method.
foreach (XmlNode xNode in nodeListName)
{
XmlElement xParentEle = xNode.ParentNode as XmlElement;
if((xParentEle != null) && xParentEle.HasAttribute("split"))
{
parentSplit = xParentEle.Attributes["split"].Value;
}
}
Just for the newcomers: the recent versions of C# allows the use of ? operator to check nulls assignments
parentSplit = xNode.ParentNode.Attributes["split"]?.Value;
You can use LINQ to XML,
XDocument doc = XDocument.Load(file);
var result = (from ele in doc.Descendants("section")
select ele).ToList();
foreach (var t in result)
{
if (t.Attributes("split").Count() != 0)
{
// Exist
}
// Suggestion from #UrbanEsc
if(t.Attributes("split").Any())
{
}
}
OR
XDocument doc = XDocument.Load(file);
var result = (from ele in doc.Descendants("section").Attributes("split")
select ele).ToList();
foreach (var t in result)
{
// Response.Write("<br/>" + t.Value);
}
var splitEle = xn.Attributes["split"];
if (splitEle !=null){
return splitEle .Value;
}
EDIT
Disregard - you can't use ItemOf (that's what I get for typing before I test). I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.
END EDIT
You can use the ItemOf(string) property in the XmlAttributesCollection to see if the attribute exists. It returns null if it's not found.
foreach (XmlNode xNode in nodeListName)
{
if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
{
parentSplit = xNode.ParentNode.Attributes["split"].Value;
}
}
XmlAttributeCollection.ItemOf Property (String)
You can use the GetNamedItem method to check and see if the attribute is available. If null is returned, then it isn't available. Here is your code with that check in place:
foreach (XmlNode xNode in nodeListName)
{
if(xNode.ParentNode.Attributes.GetNamedItem("split") != null )
{
if(xNode.ParentNode.Attributes["split"].Value != "")
{
parentSplit = xNode.ParentNode.Attributes["split"].Value;
}
}
}
Another way to handle the situation is exception handling.
Every time a non-existent value is called, your code will recover from the exception and just continue with the loop. In the catch-block you can handle the error the same way you write it down in your else-statement when the expression (... != null) returns false. Of course throwing and handling exceptions is a relatively costly operation which might not be ideal depending on the performance requirements.

Categories

Resources