I have an xml data given below. I need to check whether an employee of empName="John" exists in Production department. If exists update the salary otherwise add an employee to the department.
<Company>
<Company Name="ABCDEF" />
<Place="AKR" />
<Production>
<employee empName="John" empId="E11" salary="1000" />
<employee empName="Ivan" empId="E12" salary="3000" />
<employee empName="Paul" empId="E13" salary="1200" />
</Production>
<Marketing>
<employee empName="Keith" empId="EMP11" />
<employee empName="Christina" empId="EMP12" />
</Marketing>
</Company>
I need to check particular node exist in this data using c# linq?
Correct your XML first,
<Company>
<Company Name="ABCDEF" />
<Production>
<employee empName="John" empId="E11" salary="1000" />
<employee empName="Ivan" empId="E12" salary="3000" />
<employee empName="Paul" empId="E13" salary="1200" />
</Production>
<Marketing>
<employee empName="Keith" empId="EMP11" />
<employee empName="Christina" empId="EMP12" />
</Marketing>
</Company>
you can try like this
string filePaths = "XMLFile1.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePaths);
XmlNodeList elements = xmlDoc.GetElementsByTagName("employee");
Boolean found = false;
foreach (XmlElement element in elements)
{
if (element.GetAttribute("empName") == "John")
{
found = true;
break;
}
}
Your XML is invalid; you cannot have a node like <Place="AKR" />
But, after changing it into something valid, you could try using this LINQ statement:
XDocument root = XDocument.Parse(File.ReadAllText("xml.xml"));
IEnumerable<XElement> production = root.Root
.Descendants("Production")
.Where(x => x.Elements("employee")
.Where(e => e.Attribute("empName").Value.Equals("John"))
.Any()
);
if (production.Any())
{
Console.WriteLine("John found...");
}
else
{
Console.WriteLine("No John found");
}
try this:
XmlNode node = xmlDoc.SelectSingleNode(NodeName);
Related
I have an XML similar to below,
<?xml version="1.0" encoding="utf-8"?>
<body>
<Result>
<Students>
<Student>
<Firstname Value="Max" />
<LastName Value="Dean" />
</Student>
<Student>
<Firstname Value="Driz" />
<LastName Value="Jay" />
</Student>
</Students>
</Result>
</body>
I'm trying to figure out if its possible to write some code to dynamically build a Linq query from something like,
string pathToElements = "Result.Students.Student";
var individualItems = pathToElements.Split(".");
to something like,
XElement document = XElement.Parse(xml);
var evaluatedResult = document.Elements("Result")
.Elements("Students")
.Elements("Student")
.ToList();
basically the individualItems has 3 items "Result", "Students" and "Student". I'm exploring possible ways to create a dynamic query to accomplish something like,
document.Elements("Result")
.Elements("Students")
.Elements("Student")
.ToList();
For n number of Items I would just need to keep appending .Elements("") to the query.
Any advice on how to achieve this, my first instinct was to use a string builder and have the query as a string. I was able to do this but was not able to find out how a LINQ query which is in the form of a string can be executed.
Thanks in advance
You can query XML using XPath (it's a string so you can create it dynamically) then you can deserialize the item
https://learn.microsoft.com/en-us/troubleshoot/developer/dotnet/framework/general/query-xpathdocument-xpath-csharp
The output of this code
using System;
using System.Xml.XPath;
using System.IO;
public class Program
{
public static void Main()
{
var xml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<body>
<Result>
<Students>
<Student>
<Firstname Value=""Max"" />
<LastName Value=""Dean"" />
</Student>
<Student>
<Firstname Value=""Driz"" />
<LastName Value=""Jay"" />
</Student>
</Students>
</Result>
</body>";
using (TextReader tr = new StringReader(xml))
{
var xdoc = new XPathDocument(tr);
var nav = xdoc.CreateNavigator();
var nodeIter = nav.Select("/body/Result/Students/Student");
while (nodeIter.MoveNext())
{
Console.WriteLine("Student: {0}", nodeIter.Current.InnerXml);
};
}
}
}
is
Student: <Firstname Value="Max" />
<LastName Value="Dean" />
Student: <Firstname Value="Driz" />
<LastName Value="Jay" />
I'm trying to delete a parent from a element in XML.
My XML:
<root>
<Element1 ManagementID="10" />
<Users>
<UserID ManagementID="10">
<Identification IDValue="1" />
<!-- More elements Here -->
</UserID>
</Users>
<!-- More Users elements Here -->
I find my user my its IDValue:
XElement user = (from el in document.Root.Elements("Users").Elements("UserID ").Elements("Identification")
where (string)el.Attribute("IDValue") == myID
select el).FirstOrDefault();
Now, I would like to remove all the user.Parent.Parent
I mean delete the element:
<Users>
<UserID ManagementID="10">
<Identification IDValue="1" />
<!-- More elements Here -->
</UserID>
</Users>
** I'll have many Users elements, that's why first I look for the identification IDValue
I found the solution for who needs it:
I already had the node from my linq so
user.Parent.Parent.Remove()
var user = document.Root
.XPathSelectElements("//UserId")
.FirstOrDefault(userId => userId.Element("Identification").Attribute(XName.Get("IDValue")).Value == myID);
Try this :
List<XElement> users = document.Descendants("Users")
.Where(user => user.Elements("Identification")
.Where(el => (string)el.Attribute("IDValue") != myID)
.Any()).ToList();
XElement element1 = document.Descendants("Element1").FirstOrDefault();
element1.ReplaceNodes(users);
I have an XML in this Format and I want to get List of Line ID and its Name
<ArrayOfLines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<LineStatus ID="0" StatusDetails="">
<BranchDisruptions />
<Line ID="1" Name="Line1" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
<LineStatus ID="1" StatusDetails="">
<BranchDisruptions />
<Line ID="2" Name="Line2" />
<Status ID="GS" CssClass="GoodService" Description="Good Service" IsActive="true">
<StatusType ID="1" Description="Line" />
</Status>
</LineStatus>
</ArrayOfLines>
and This is the code I have written:
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = from c in xmlFile.Descendants("LineStatus") select c;
but it is not returning me any results.
Here is my idea but you have to create list "namesList" and "idList" before. Try this:
XDocument xDoc = XDocument.Load("your xml file");
foreach (var elem in xDoc.Document.Descendants("line"))
{
idList.Add(elem.Attribute("ID").Value);
namesList.Add(elem.Attribute("Name").Value);
}
And you have full controll by index of each list to this data. After that you can also create object of these 2 elements
You have an xml namespace, you need to specify it with element names:
XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
var query = from c in xmlFile.Descendants(ns + "LineStatus") select c;
Try this...
String xmlFilePath = #"C:/myXML.xml";
XDocument xmlFile = XDocument.Load(xmlFilePath);
var query = (from c in xmlFile.Descendants("Line")
select new {
ID=c.Attribute("ID").Value,
Name=c.Attribute("Name").Value
}).ToList();;
I have a Xml and i have to get the element name
<Data>
<Test key="G" modifier="control" />
<Test1 key="E" modifier="control" />
<Test3 />
<Test4 />
</Data>
XDocument xd = XDocument.Load("..\\Cmd.xml");
IEnumerable<XElement> xeCmdData = Cmd.XPathSelectElements(".//Data");
foreach (XElement xeData in xeCmdData)
{
// here i am getting the whole xml how to get Element name ...
// Like <Data>
// <Test key="G" modifier="control" />
// <Test1 key="E" modifier="control" />
// <Test3 />
// <Test4 />
// </Data>
}
How to get Element names ?
XDocument xd = XDocument.Load("..\\Cmd.xml");
IEnumerable<string> names = xd.XPathSelectElements("//Data/*")
.Select(e => e.Name.LocalName);
Or without XPath
IEnumerable<string> names = xd.Descendants("Data")
.Elements()
.Select(e => e.Name.LocalName);
Result:
Test
Test1
Test3
Test4
I'm new to C# and want to manipulate a external xml file. Here is that file:
<results>
<root />
<category id="" title="" />
<category />
<category />
</results>
I want this to be modified something like:
<results>
<root />
<categories>
<category id="" title=""/>
<category />
<category />
</categories>
</results>
This works, it replaces all of the elements named category found directly under the root element (root element is results) and adds new element named categories. category elements are then added to categories and category elements are removed from under the results element. In the end categories element is added. You can also save the document by calling it's Save method:
XDocument doc = XDocument.Load("Data.xml");
var categoriesElement = new XElement("categories");
var categoryElements = doc.Root.Elements("category");
foreach(var el in categoryElements.ToList())
{
categoriesElement.Add(new XElement(el));
el.Remove();
}
doc.Element("results").Add(categoriesElement);
//doc.Save(<filepath>);
XElement elem = XElement.Parse(xml);
elem = new XElement("results",
new XElement("root", elem.Element("root").Value),
new XElement("categories", elem.Descendants("category"))
);
Ideally the xml can be transformed using xslt. Basics on xslt transforation can be found below,
http://support.microsoft.com/kb/307322
http://www.w3schools.com/xsl/
Using xslt makes you solution or code more managable. Hope this helps