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();
Related
I want to select xml node based on attribute. I'm very new to how linq to xml works, and can't write proper query. How can I fix it?
My XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Enable0" value="true" />
<!-- dumb comment -->
<add key="Enable1" value="false" />
<!-- dumb comment1-->
<add key="Enable2" value="true" />
<add key="Enable3" value="false" />
<!-- dumb comment2 -->
<add key="Enable4" value="true" />
</appSettings>
<asdf>
<a key="b"></a>
<a key="c"></a>
<a key="d"></a>
</asdf>
</configuration>
My attempt:
private string GetAttribute(string name)
{
//???
var query = from node in deafultElement.Elements("add")
where node.Attribute("key").Value == name
select node.Attribute("value").value;
return query.toString();
//currently returns "System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]"
}
You can also use linq methods' syntax to reach the same result.
string value = defaultElement.Elements("add")
.FirstOrDefault(n => n.Attribute("key").Value == name)
.Attribute("value").Value;
var query = (from node in deafultElement.Elements("add")
where node.Attribute("key").Value == name
select node.Attribute("value").Value).FirstOrDefault();
return query
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
Can anyone help on how to process the information within Fields only when the Condition is True ?
I've tried For each and if then but I would like something more graceful.
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<Events>
<Event Id="1">
<Condition>True</Condition>
<Fields>
<Parameter Name="thisOne" Value="1234" />
<Parameter Name="notthisOne" Value="xyz" />
<Parameter Name="thisoneagain" Value="5678" />
<Parameter Name="notthisoneAgain" Value="abc" />
</Fields>
</Event>
<Event Id="2">
<Condition>False</Condition>
<Fields>
<Parameter Name="thisOne" Value="1234" />
<Parameter Name="notthisOne" Value="xyz" />
<Parameter Name="thisoneagain" Value="5678" />
<Parameter Name="notthisoneAgain" Value="abc" />
</Fields>
</Event>
</Events>
</root>
This should do it:
var paramSets = e.Descendants("Event")
.Where(ev => (string)ev.Element("Condition") == "True")
.Select(ev => ev.Descendants("Parameter")
.Select(p => new
{
Name = (string)p.Attribute("Name"),
Value = (string)p.Attribute("Value")
}));
This will select a set of parameters for each Event element where Condition is True. In other words, the type of paramSets is IEnumerable<IEnumerable<T>>, where T is an anonymous type with a Name and Value property.
You can loop through it like this:
foreach (var event in paramSets)
{
foreach (var parameter in event)
{
// Do something with the parameter
Console.WriteLine("Name: {0}, Value: {1}", parameter.Name, parameter.Value);
}
}
Use the Where Clause to restrict the set of data in LINQ to XML.
You can get the value of a particular element by drilling down into the element and calling .Value
This will load all the name and value for all the each parameter that is part of an Event that has a condition element with a value of True:
Dim xdoc As XDocument = XDocument.Parse(str)
Dim parameters = From e In xdoc.Root.Elements("Events").Elements("Event")
From p In e.Elements("Fields").Elements("Parameter")
Where e.Element("Condition").Value = "True"
Select New With {
.Name = p.Attribute("Name").Value,
.Value = p.Attribute("Value").Value
}
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.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<eRecon xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="eRecon.xsd">
<Header>
<Company Code="" />
<CommonCarrierCode />
<InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName>
<BatchNumber>000152</BatchNumber>
<InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime>
<InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime>
<RecordCount>8</RecordCount>
</Header>
<Detail>
<CarrierStatusDate>2010-01-11</CarrierStatusDate>
<ClaimNum>YDF02892 C</ClaimNum>
<InvoiceNum>0108013775</InvoiceNum>
<LineItemNum>001</LineItemNum>
<NABP>10600211</NABP>
<RxNumber>4695045</RxNumber>
<RxDate>2008-07-21</RxDate>
<CheckNum />
<PaymentStatus>PENDING</PaymentStatus>
<RejectDescription />
<InvoiceChargeAmount>152.15</InvoiceChargeAmount>
<InvoicePaidAmount>131.00</InvoicePaidAmount>
</Detail>
</eRecon>
How can I extract the portion
<Header>
<Company Code="" />
<CommonCarrierCode />
<InputFileName InputIDPk="">F:\ReconNew\TmesysRec20100111.rec</InputFileName>
<BatchNumber>000152</BatchNumber>
<InputStartDateTime>2010-02-26 11:47:00</InputStartDateTime>
<InputFinishDateTime>2010-02-26 11:47:05</InputFinishDateTime>
<RecordCount>8</RecordCount>
</Header>
from the above xml file.
I need the c# code to extract a part of xml tag from an xml file.
If the file isn't too big (smaller than a few MB), you can load it into an XmlDocument:
XmlDocument doc = new XmlDocument();
doc.Load(#"C:\yourfile.xml");
and then you can parse for the <Header> element using an XPath expression:
XmlNode headerNode = doc.SelectSingleNode("/eRecon/Header");
if(headerNode != null)
{
string headerNodeXml = headerNode.OuterXml;
}
You can use XPath like in this tutorial:
http://www.codeproject.com/KB/cpp/myXPath.aspx
Use Linq-to-xml:
XDocument xmlDoc = XDocument.Load(#"c:\sample.xml");
var header = xmlDoc.Descendants("Header").FirstOrDefault();
Linq version
string fileName=#"d:\xml.xml";
var descendants = from i in XDocument.Load(fileName).Descendants("Header")
select i;