Get max attribute value from XML using LINQ - c#

I have the following XML file. I want to get Max("NR") using LINQ. Could anyone help me to do this? I know how to do this for nodes, but attributes made me confused... :S
<?xml version="1.0" encoding="utf-8"?>
<SMPyramid LayerName="qwe" LayerPath="D:\#PYRAMID\qwe" Extension=".png" Meters="100000" RasterSize="4000">
<Level NR="0" RasterXSize="512" RasterYSize="512" LastTileXSize="416" LastTileYSize="416" MinX="400000" MaxX="500000" MinY="1200000" MaxY="1300000" ScaleFactor="25" TilesCountX="8" TilesCountY="8" />
<Level NR="1" RasterXSize="512" RasterYSize="512" LastTileXSize="323" LastTileYSize="323" MinX="400000" MaxX="499980.9024" MinY="1200019.0976" MaxY="1300000" ScaleFactor="34.679466666666663" TilesCountX="6" TilesCountY="6" />
<Level NR="2" RasterXSize="512" RasterYSize="512" LastTileXSize="414" LastTileYSize="414" MinX="400000" MaxX="499738.14613333333" MinY="1200261.8538666666" MaxY="1300000" ScaleFactor="69.358933333333326" TilesCountX="3" TilesCountY="3" />
<Level NR="3" RasterXSize="512" RasterYSize="512" LastTileXSize="206" LastTileYSize="206" MinX="400000" MaxX="499599.42826666665" MinY="1200400.5717333332" MaxY="1300000" ScaleFactor="138.71786666666665" TilesCountX="2" TilesCountY="2" />
<Level NR="4" RasterXSize="358" RasterYSize="358" LastTileXSize="358" LastTileYSize="358" MinX="400000" MaxX="499321.99253333331" MinY="1200678.0074666666" MaxY="1300000" ScaleFactor="277.4357333333333" TilesCountX="1" TilesCountY="1" />
</SMPyramid>

You treat attributes exactly the same way you would as nodes. So for example:
int maxNr = doc.Descendants("Level")
.Max(x => (int) x.Attribute("NR"));
Note that that will give you the maximum value of NR, not the Level element which contains that number. For that, you'd want to either use OrderByDescending(...).First() or use MaxBy from MoreLINQ.

XDocument xDoc = XDocument.Load(#" your XML file path ");
int maxNr = xDoc.Root.Elements().Max(x => (int)x.Element("NR"));
After you specify the file path, you can get "NR" using the Element.

Related

Getting attributes from xml using Linq

I have an xml document that I want to obtain attributes from
Here is the XML:
<Translations>
<Product Name="Room" ID="16">
<Terms>
<Term Generic="Brand" Product="Sub Category" />
<Term Generic="Range" Product="Brand" />
</Terms>
</Product>
<Product Name="House"" ID="29">
<Terms>
<Term Generic="Category" Product="Product Brand" />
<Term Generic="Brand" Product="Category Description" />
<Term Generic="Range" Product="Group Description" />
<Term Generic="Product" Product="Product Description" />
</Terms>
</Product>
</Translations>
Here is my current Linq query
public static string clsTranslationTesting(string GenericTerm, int ProductID)
{
const string xmlFilePath = "C:\\Dev\\XMLTrial\\XMLFile1.xml";
var xmlDocument = XDocument.Load(xmlFilePath);
var genericValue =
from gen in xmlDocument.Descendants("Product")
where gen.Attribute("ID").Value == ProductID.ToString()
select gen.Value.ToString();
}
The error that I am having is when I pass data into the method, the method loads the xml from the file to the xmlDocument variable successfully. However when it executes the query it returns a value null. I want to obtain the ID value.
I'm a little lost with your question, but here's my attempt.
First thing is you need to change "Customer" to "Product". Your XML contains not a single instance of the word "Customer" so I think you have a typo there.
I don't know exactly what you want returned from the query (I assume just the entire matched node?). Try this:
var genericValue = xmlDocument.Descendants("Product")
.FirstOrDefault(x => x.Attribute("ID").Value == "16");
I made a fiddle here that shows it in action

How to extract specific nodes from an xml file with their parents?

I have an xml file from which I want to extract nodes whose id attribute is "Needed":
<root>
<level1 id="NotNeeded">
</level1>
<level1 id="Needed">
<level2 id="Needed">
<level3 id="Needed">I need this one</level3>
<level3 id="NotNeeded1">I don't need this one</level3>
</level2>
<level2 id="notNeeded">
<level3 id="notNeeded">I don't need this one</level3>
</level2>
</level1>
</root>
(Depth is arbitrary)
I need to transform it into the following form:
<root>
<level1 id="Needed">
<level2 id="Needed">
<level3 id="Needed">I need this one</level3>
</level2>
</level1>
</root>
What I'm trying to do (with pseudocode, I hope it's clear):
myextraction=[element with id "Needed"]
while [myextraction has parent]
{
myextraction=myextraction.[parent without children].Addtochildren(myextraction)
}
Is there an easier way to do this? (A built-in method maybe?)
You could use Linq to Xml and do this.
XDocument doc = XDocument.Load(filepath);
doc.Descendants()
.Where(x=>x.Attribute("id") != null && x.Attribute("id").Value == "NotNeeded")
.Remove();
Ouput :
<root>
<level1 id="Needed">
<level2 id="Needed">
<level3 id="Needed">I need this one</level3>
</level2>
</level1>
</root>
Check this fiddle

xml parsing and convert values to string C#

I have an XML format like this
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<abresponse IssuerId="5" ReturnCode="Success" Version="12.2">
<XMLAuthenticateResponse>
<ACL>
<ACL Name="PM.ADMIN" Value="1" />
<ACL Name="PM.APPROVE" Value="1" />
<ACL Name="PM.LOGIN" Value="1" />
<ACL Name="PM.SUPPORT" Value="1" />
</ACL>
<User EMailAddress="abc#xyz.com" GroupName="Program Administrator" UserId="2095965" Username="test" />
</XMLAuthenticateResponse>
</abresponse >
How can i take the ReturnCode from the XML..
I am getting this as a API Response, so i have converted that
XElement response = XElement.Parse(xDoc.OuterXml)
string retcode=response.Descendants("OrbiscomResponse")
.Attributes("ReturnCode")
.FirstOrDefault()
.Value
.Tostring();
Just remove the Descendants call and it should work fine:
string retcode = response
.Attributes("ReturnCode")
.FirstOrDefault()
.Value
.ToString();

Replacing Some Elements in XML [Sample XML Provided]

I have an xml document that looks like this.I have a XML file structured as below.
Sample XML is as follows:
<Dr.Watson>
<Bugs>
<Bug Name="Bug.add --> AAAAAAAAAAAA">
<criteria>
<includeFilterSets>
<filterSet>
<filter>
<filterName>PRODUCT_NAME</filterName>
<operator>
<name>Equals</name>
</operator>
<value>Dr.Watson</value>
</filter>
</filterSet>
</includeFilterSets>
<grouping>
<groupBy>
<name>STATUS</name>
</groupBy>
</grouping>
<caseSensitive>false</caseSensitive>
<entityToSearch>
<name>BUG</name>
</entityToSearch>
</criteria>
</Bug>
</Bugs>
</Dr.Watson>
I want to replace some of elements in the XML file like below:
<Dr.Watson>
<Bugs>
<Bug Name="Bug.add --> AAAAAAAAAAAA">
<criteria>
<includeFilterSets>
<filterSet>
<filter>
<filterName>PRODUCT_NAME</filterName>
<operator>
<name>Equals</name>
</operator>
<value>Dr.Watson</value>
</filter>
</filterSet>
</includeFilterSets>
<grouping>
<groupBy>
<name>STATE</name>
</groupBy>
</grouping>
<caseSensitive>false</caseSensitive>
<entityToSearch>
<name>BUG</name>
</entityToSearch>
</criteria>
</Bug>
</Bugs>
</Dr.Watson>
i would like to change the available under followed by as State.
Please suggest.
var xdoc = XDocument.Load(path_to_xml);
var groupByName = xdoc.XPathSelectElement("//groupBy/name");
groupByName.Value = "STATE";
xdoc.Save(path_to_xml);

Extract a node from xml response

Below is my response generated from a webservice.
I want to do such that I want only PresentationElements node from this response.
Any help how can I achieve this query?
<?xml version="1.0"?>
<GetContentResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ExtensionData />
<GetContentResult>
<ExtensionData />
<Code>0</Code>
<Value>Success</Value>
</GetContentResult>
<PresentationElements>
<PresentationElement>
<ExtensionData />
<ContentReference>Product View Pack</ContentReference>
<ID>SHOPPING_ELEMENT:10400044</ID>
<Name>View Pack PE</Name>
<PresentationContents>
<PresentationContent>
<ExtensionData />
<Content>View Pack</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Name</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>Have more control of your home's security and lighting with View Pack from XFINITY Home.</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Description</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>/images/shopping/devices/xh/view-pack-2.jpg</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Image</Name>
</PresentationContent>
<PresentationContent>
<ExtensionData />
<Content>The View Pack includes:
2 Lighting / Appliance Controllers
2 Indoor / Outdoor Cameras</Content>
<ContentType>TEXT</ContentType>
<Language>ENGLISH</Language>
<Medium>COMPUTER_BROWSER</Medium>
<Name>Feature1</Name>
</PresentationContent>
</PresentationContents>
</PresentationElement>
</PresentationElements>
</GetContentResponse>
You can use XPath extensions
var xdoc = XDocument.Parse(response);
XElement presentations = xdoc.XPathSelectElement("//PresentationElements");
You may use the System.Xml.Linq.XDocument:
//Initialize the XDocument
XDocument doc = XDocument.Parse(yourString);
//your query
var desiredNodes = doc.Descendants("PresentationElements");
Pretty easy, have you tried:
XDocument xml = XDocument.Load("... xml");
var nodes = (from n in xml.Descendants("PresentationElements")
select n).ToList();
You could also project each individual node to an anonymous type using something like:
select new
{
ContentReference = (string)n.Element("ContentReference").Value,
.... etc
}

Categories

Resources