I do have following xml:
<Assembly>
<Bench>
<Typ>P1</Typ>
<DUT>
<A>6</A>
</DUT>
</Bench>
<Bench>
<Typ>P2</Typ>
<DUT>
<A>6</A>
</DUT>
</Bench>
</Assembly>
How can I get a reference to 'P2'-element that I can insert a new DUT? I tried following code which gives me an error:
var xElement = xmlDoc.Element("Assembly")
.Elements("Bench")
.Where(item => item.Attribute("Typ").Value == "P2")
.FirstOrDefault();
xElement.AddAfterSelf(new XElement("DUT"));
thanks in advance
Typ is element name, not an attribute. If you meant to add new <DUT> element after existing <DUT> under the second <Bench>, this slight change to the code you've tried should work :
var xElement = xmlDoc.Element("Assembly")
.Elements("Bench")
.FirstOrDefault(item => item.Element("Typ").Value == "P2");
xElement.AddAfterSelf(new XElement("DUT"));
Another way of doing the same thing, just to show the options available.
XElement typ = xmlDoc.Descentants("Typ")
.FirstOrDefault(typ => ((string)typ) == "P2");
You can use the same AddAfterSelf as har07, or .Parent.Add() if it doesn't matter where in the parent Bench it goes. Add will add it as the last element.
typ.Parent.Add(new XElement("DUT"));
Related
I am trying to get all descendant XElements including root element of an XElement according to presence of specific attribute. My not very nice attempt:
var myXElements = form.FormData.Descendants().Where(e => e.Attributes().Where(a => a.Name == myProperty).Count() > 0).ToList();
// Extra for root element
if (form.FormData.Attribute(myProperty) != null)
{
myXElements.Add(form.FormData);
}
where form.FormData is XElement type (I recive it from .dll) and myProperty is the specific property.
Is there more elegent way to achive this?
var myXElements = form.FormData.DescendantsAndSelf().Where(e => e.Attribute(myProperty) != null).ToList()
I want to check that if the "< city>" node 'having a specific value (say Pathankot )' already exist in the xml file under the a particular "< user Id="any"> having a specific Id", before inserting a new city node into the xml.
< users>
< user Id="4/28/2015 11:29:44 PM">
<city>Fazilka</city>
<city>Pathankot </city>
<city>Jalandher</city>
<city>Amritsar</city>
</user>
</users>
In order to insert I am using the Following c# code
XDocument xmlDocument = XDocument.Load(#"C:\Users\Ajax\Documents\UserSelectedCity.xml");
string usrCookieId = Request.Cookies["CookieId"].Value;
xmlDocument.Element("Users")
.Elements("user")
.Single(x => (string)x.Attribute("Id") == usrCookieId)
//Incomplete because same named cities can be entered more that once
//need to make delete function
.Add(
new XElement("city", drpWhereToGo.SelectedValue));
My Questions:
How Can i check weather the < city> node having specific value say
Pathankot already exist in the xml file Before Inserting a new city
node.
I am Using absolute Path in" XDocument xmlDocument =
XDocument.Load(#"C:\Users\Ajax\Documents\Visual Studio
2012\WebSites\punjabtourism.com\UserSelectedCity.xml");" This
does not allow me to move the files to new folder without changing
the path which is not desirable. But if i use the relative path The
Error Occures "Access Denied";
I would use this simple approach:
var query =
xmlDocument
.Root
.Elements("user")
.Where(x => x.Attribute("Id").Value == usrCookieId)
.Where(x => !x.Elements("city").Any(y => y.Value == "Pathankot"));
foreach (var xe in query)
{
xe.Add(new XElement("city", drpWhereToGo.SelectedValue));
}
It's best to avoid using .Single(...) or .First(...) if possible. The description of your problem doesn't sound like you need to use these though.
Try this:-
First load the XML file into XDocument object by specifying the physical path where your XML file is present. Once you have the object just take the First node with matching condition (please note I am using First instead of Single cz you may have multiple nodes with same matching condition, Please see the Difference between Single & First)
XDocument xmlDocument = XDocument.Load(#"YourPhysicalPath");
xmlDocument.Descendants("user").First(x => (string)x.Attribute("Id") == "1"
&& x.Elements("city").Any(z => z.Value.Trim() == "Pathankot"))
.Add(new XElement("city", drpWhereToGo.SelectedValue));
xmlDocument.Save("YourPhysicalPath");
Finally add the required city to the node retrieved from the query and save the XDocument object.
Update:
If you want to check first if all the criteria fulfills then simply use Any like this:-
bool isCityPresent = xdoc.Descendants("user").Any(x => (string)x.Attribute("Id") == "1"
&& x.Elements("city").Any(z => z.Value.Trim() == "Pathankot"));
I'd create an extension to clean it up a bit, and use XPath for the search.
public static class MyXDocumentExtensions
{
public static bool CityExists(this XDocument doc, string cityName)
{
//Contains
//var matchingElements = doc.XPathSelectElements(string.Format("//city[contains(text(), '{0}')]", cityName));
//Equals
var matchingElements = doc.XPathSelectElements(string.Format("//city[text() = '{0}']", cityName));
return matchingElements.Count() > 0;
}
}
And call it like that:
XDocument xmlDocument = XDocument.Load("xml.txt");
var exists = xmlDocument.CityExists("Amritsar");
Expanding on your question in the comment, you can then use it as:
if(!xmlDocument.CityExists("Amritsar"))
{
//insert city
}
If you would like to match regardless of the trailing whitespace in the XML, you can wrap the text() call in XPath with a normalize-space:
var matchingElements = doc.XPathSelectElements(string.Format("//city[normalize-space(text()) = '{0}']", cityName.Trim()));
I have problem i'm trying to update a specific part of the XML with the linq query but it doesn't work. So i an xml file:
<?xml version="1.0" encoding="utf-8"?>
<DesignConfiguration>
<Design name="CSF_Packages">
<SourceFolder>C:\CSF_Packages</SourceFolder>
<DestinationFolder>C:\Documents and Settings\xxx</DestinationFolder>
<CopyLookups>True</CopyLookups>
<CopyImages>False</CopyImages>
<ImageSourceFolder>None</ImageSourceFolder>
<ImageDesinationFolder>None</ImageDesinationFolder>
</Design>
</DesignConfiguration>
I want to select the part where the part where there is Design name="somethning" and get the descendants and then update the descendants value that means this part:
<SourceFolder>C:\CSF_Packages</SourceFolder>
<DestinationFolder>C:\Documents and Settings\xxx</DestinationFolder>
<CopyLookups>True</CopyLookups>
<CopyImages>False</CopyImages>
<ImageSourceFolder>None</ImageSourceFolder>
<ImageDesinationFolder>None</ImageDesinationFolder>
I have this code:
XDocument configXml = XDocument.Load(configXMLFileName);
var updateData = configXml.Descendants("DesignConfiguration").Elements().Where(el => el.Name == "Design" &&
el.Attribute("name").Value.Equals("CSF_Packages")).FirstOrDefault();
configXml.Save(configXMLFileName);
I'm getting the null data in the updateData varibale. When I'm trying the Descendat's function through QuickWatch it also returns a null value. When I'm checking the configXML variable it has data that is my whole xml. What am I doing wrong?
Try this:
var updateData =
confixXml
.Root //Root Element
.Elements("Design") //All elements under root called Design
.Where(element => (String)element.Attribute("name") == "AFP_GRAFIKA") //Find the one with the name Attribute of AFP_GRAFIKA
.FirstOrDefault(); //Grab the first one it finds or return null.
if (updateData != null)
{
var myElements =
updateData
.Elements(); //All the elements under the Design node
}
XDocument xml = XDocument.Load("");
XElement settings = (from children in xml.Descendants("DesignConfiguration")
where children.Name.Equals("Design") && children.Attribute("name").Equals("CSF_Packages")
select children).FirstOrDefault();
settings.Element("SourceFolder").SetValue("filepath");
settings.Element("CopyImages").SetValue(true);
Ok, so I've managed to fix the problem. I don't know why but it worked. It seems that the Descendants function returns null as a stand alone function but with linq it works. So for my solution only thing what should be done is this:
var updateData = (from s in configXml.Descendants("Design")
where s.Attribute("name").Value == design.DesignName
select s).First();
At first before I sent you my question I've tried this but I didn't have the select s part. Besides when I wrote the where s.Atribute part in the curly brackets I've inserted the design.DesignName object instead of the name of the attribute. So no it works ok. Thanks for your help and everything. Til nex time. Have a nice day/night everyone :)
Because DesignConfiguration was your root node, the Descendants("DesignConfiguration) was returning null. By using the .Descendants("Design"), you were looking at child nodes, not the self.
Here's my XML File:
<Applications>
<Application Name="Abc">
<Section Name="xyz">
<Template Name="hello">
...
....
</Template>
</Section>
</Application>
<Application Name="Abc1">
<Section Name="xyz1">
<Template Name="hello">
...
....
</Template>
</Section>
</Application>
What I need to do is get the Template XElement from the given structure based upon the Name attribute of Template tag. The problem is there can be multiple template tags with same attribute Name. The Distinguishing factor is Application Name attribute value and section attribute value.
Currently I'm able to get the XElement by first getting Application Element based upon it's attribute, then Section based upon it's attribute and then finally template based upon it' name.
I wanted to know if there is a way to get it in one go.
I would use the fact that you can call Elements or an existing sequence, so:
var template = doc.Descendants("Application")
.Where(x => (string) x.Attribute("Name") == applicationName)
.Elements("Section")
.Where(x => (string) x.Attribute("Name") == sectionName)
.Elements("Template")
.Where(x => (string) x.Attribute("Name") == templateName)
.FirstOrDefault();
You might even want to add an extension method somewhere:
public static IEnumerable<XElement> WithName(this IEnumerable<XElement> elements,
string name)
{
this elements.Where(x => (string) x.Attribute("Name") == name);
}
Then you can rewrite the query as:
var template = doc.Descendants("Application").WithName(applicationName)
.Elements("Section").WithName(sectionName)
.Elements("Template").WithName(templateName)
.FirstOrDefault();
... which I think you'll agree is quite readable :)
Note that the use of casting XAttribute to string instead of using the Value property means that any elements without the Name attribute are just effectively ignored rather than causing a NullReferenceException.
The following code should do the trick:
var template = doc.Descendants("Template")
.Where(x => x.Attribute("Name").Value == "hello"
&& x.Parent.Attribute("Name").Value == "xyz1"
&& x.Parent.Parent.Attribute("Name").Value == "Abc1");
Please note that this code throws exceptions if the XML doesn't conform to the specification. Specifically, there will be a NullReferenceException if any of the tags in question don't contain an attribute named "Name". Or if the Template tag doesn't have two levels of parents.
XDocument doc = XDocument.Load("Path of xml");
var selection =
doc.Descendants("Section").Select(item => item).Where(
item => item.Attribute("Name").Value.ToString().Equals("Section Name Value")).ToList();
if(null != selection)
{
var template =
selection.Descendants("Template").Select(item => item).Where(
item => item.Attribute("Name").Value.ToString().Equals("Template name value"));
}
XPath should help you. Use the Extensions.XPathSelectElement Method (XNode, String) :
XDocument xdoc = XDocument.Load("yourfile.xml");
string xPathQuery = string.Format(
"/Applications/Application[#Name='{0}']/Section[#Name='{1}']/Template[#Name='{2}']",
"MyApplication",
"MySection",
"MyTemplate"
);
XElement template = xdoc.Root.XPathSelectElement(xPathQuery);
I am returning a list. This is contains the names of xml nodes that cannot be blank in my XML file.
List<Setting> settingList = SettingsGateway.GetBySettingTypeList("VerifyField");
I have a LINQ Statement. I am trying to return all transactions that have empty nodes. The list here is returning the nodes that CANNOT be empty. Does anyone know what I am doing wrong here?
The following code is supposed to Bind the "transactions" to a DataGrid and display the Txn's that have empty nodes which are required.
var transactionList =
from transactions in root.Elements(XName.Get("Transactions")).Elements().AsEnumerable()
where transactions.Elements().Any
(
el =>
//String.IsNullOrEmpty(el.Value) &&
//elementsThatCannotBeEmpty.Contains(el.Name)
settingList.Any(
name => String.IsNullOrEmpty(el.Element(name.SettingValue).Value)
)
)
select new
{
CustomerName = transactions.Element(XName.Get("CustomerName")).Value,
ConfirmationNumber = transactions.Element(XName.Get("ConfirmationNumber")).Value
};
GridView.DataSource = transactionList;
GridView.DataBind();
XML File Example:
<OnlineBanking>
<Transactions>
<Txn>
<UserName>John Smith</UserName>
<CustomerStreet>123 Main</CustomerStreet>
<CustomerStreet2></CustomerStreet2>
<CustomerCity>New York</CustomerCity>
<CustomerState>NY</CustomerState>
<CustomerZip>12345</CustomerZip>
</Txn>
</Transactions>
</OnlineBanking>
Okay, first problem: if the element is missing, you'll get a NullReferenceException.
I'd suggest creating a List<string> of the elements which can't be null, to make the query simple. Then:
var requiredElements = settingList.Select(x => x.SettingValue).ToList();
var transactionList = root
.Elements("Transactions")
.Elements("Txn")
.Where(x => requiredElements
.Any(name => string.IsNullOrEmpty((string) x.Element(name)));
I think that should be okay, and slightly simpler than your original code... but to be honest, your original code looks like it should have worked anyway. What did it actually do? You haven't been very clear about the actual results versus the expected ones...
Something like this:
var transactionList =
root
.Elements(XName.Get("Transactions")) //Get <Transaction> elements
.Elements() //Get <Txn> elements
.Where(txn => txn.Elements().Any(e => e.Value == String.Empty)) //Filter <Txn> Elements if it have any element like this: <CustomerStreet2></CustomerStreet2>
.Select(x => new {
PropertyX = x.Element(XName.Get("UserName")),
PropertyY = x.Element(XName.Get("CustomerStreet")),
...
});
Works with:
<OnlineBanking>
<Transactions>
<Txn> <!-- This one matches! -->
<UserName>John Smith</UserName>
<CustomerStreet>123 Main</CustomerStreet>
<CustomerStreet2></CustomerStreet2>
<CustomerCity>New York</CustomerCity>
<CustomerState>NY</CustomerState>
<CustomerZip>12345</CustomerZip>
</Txn>
<Txn> <!-- This one doesn't match! -->
<UserName>John Smith</UserName>
<CustomerStreet>123 Main</CustomerStreet>
<CustomerStreet2>ASDASD</CustomerStreet2>
<CustomerCity>New York</CustomerCity>
<CustomerState>NY</CustomerState>
<CustomerZip>12345</CustomerZip>
</Txn>
</Transactions>
</OnlineBanking>