I just want to select the content of user list="default" or user list="otherListName" from a variable.
Like when my variable is equal to default I want to select the content of user list="default". By content I mean:
<list nom="Nom" description="Description" image="no_image.png"/>
And I want this content to be parse into a list
<list nom="" description="" image=""/>
<list nom="" description="" image=""/>
<?xml version="1.0" encoding="utf-8"?>
<database>
<user list="default">
<list nom="Nom" description="Description" image="no_image.png"/>
</user>
<user list="otherListName">
<list nom="" description="" image=""/>
<list nom="" description="" image=""/>
</user>
</database>`
I hope that my question is understandable.
You can use LINQ-to-XML, for example, assuming that doc is an XDocument variable containing the original XML :
var listName = "default";
var result = doc.Root
.Elements("user")
.Where(o => (string)o.Attribute("list") == listName)
.Elements("list");
See live demo in dotnetfiddle :
var raw = #"<?xml version='1.0' encoding='utf-8'?>
<database>
<user list='default'>
<list nom='Nom' description='Description' image='no_image.png'/>
</user>
<user list='otherListName'>
<list nom='' description='' image=''/>
<list nom='' description='' image=''/>
</user>
</database>";
var doc = XDocument.Parse(raw);
var listName = "default";
var result = doc.Root
.Elements("user")
.Where(o => (string)o.Attribute("list") == listName)
.Elements("list");
foreach(var r in result)
{
Console.WriteLine(r.ToString());
}
output : (for listName = "default")
<list nom="Nom" description="Description" image="no_image.png" />
Related
I am having problems with getting descendant with specific name. I have hugh XML that basically is made of lots of this elements:
<?xml version="1.0" encoding="utf-8"?>
<Search_Results xmlns="https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd">
<Entity Record="28" ResultID="12460985">
<GeneralInfo>
<EntityType>Individual</EntityType>
<Name>Jón Jónsson</Name>
<DOB>01/01/0001</DOB>
<DOBParsed />
<AccountID>ABS-ASSOC-10-109</AccountID>
<IDLabel>Account ID</IDLabel>
<IDNumber>ABS-ASSOC-10-109</IDNumber>
<AddressType>Current</AddressType>
<PostalCode>Somalia</PostalCode>
</GeneralInfo>
<RecordDetailInfo>
<EntityType>Individual</EntityType>
<SearchDate>2016-05-13 09:53:50Z</SearchDate>
<Origin>Automatic Batch</Origin>
<FirstName>Jón</FirstName>
<LastName>Jónsson</LastName>
<FullName>Jón Jónsson</FullName>
<AdditionalInfo>
<Type>Date of Birth</Type>
<Information>01/01/0001</Information>
</AdditionalInfo>
<Addresses>
<Type>Current</Type>
<PostalCode>Somalia</PostalCode>
</Addresses>
<Identifications>
<Type>Account ID</Type>
<Number>ABS10-109</Number>
</Identifications>
</RecordDetailInfo>
<WatchList>
<Match ID="1">
<EntityName>Jonsson</EntityName>
<EntityScore>96</EntityScore>
<BestName>Jonsson, Jon Orn</BestName>
<BestNameScore>96</BestNameScore>
<FileName>WorldCompliance - Full.BDF</FileName>
<SourceDate>2016-05-11 05:01:00Z</SourceDate>
<DistributionDate>2016-05-12 14:59:39Z</DistributionDate>
<ResultDate>2016-05-13 09:53:50Z</ResultDate>
<EntityUniqueID>WX0003219444</EntityUniqueID>
<MatchDetails>
<Entity Type="2">
<Number>3219444</Number>
<Date>9/3/2012</Date>
<Reason>International</Reason>
<CheckSum>69185</CheckSum>
<Gender>Male</Gender>
<Name>
<First>Jon Orn</First>
<Last>Jonsson</Last>
<Full>Jon Orn Jonsson</Full>
</Name>
<Notes>Source.</Notes>
<Addresses>
<Address ID="1" Type="4">
<Country>Iceland</Country>
</Address>
</Addresses>
<IDs>
<ID ID="1" Type="27">
<Number>3219444</Number>
</ID>
</IDs>
<Descriptions>
<Description ID="1" Type="10">
<Value>Honorary Consul of Iceland in Saskatchewan, Canada</Value>
<Notes>Starting 2002 Ending 2014</Notes>
</Description>
<Description ID="2" Type="22">
<Value>Link to WorldCompliance Online Database</Value>
<Notes>Jonsson, Jon Orn | https://members.worldcompliance.com/metawatch2.aspx?id=e0399c29-7c5e-4674-874c-f36fdb19052e</Notes>
</Description>
<Description ID="3" Type="22">
<Value>Sources of Record Information</Value>
<Notes>http://brunnur.mfa.is/interpro/utanr/HBvefur.nsf/Pages/IslSendiradIsl?OpenDocument& | CountryNr=1(Canada)& | Lang=44') | http://www.international.gc.ca/protocol-protocole/assets/pdfs/Diplomatic_List.pdf | http://www.inlofna.org/Elfros/newsletter%20January%202010.pdf | http://publications.gc.ca/collections/Collection/E12-3-2002E.pdf | http://www.onlygolfnews.com/golf-canada-saskatchewan/saskatchewan-golf-first-fort-lacrosse-ted-brandon-over-new-last-snow.htm | http://www.ops.gov.sk.ca/Consular-Officers</Notes>
</Description>
</Descriptions>
</Entity>
</MatchDetails>
</Match>
</WatchList>
</Entity>
</Search_Results>
I am trying to reach all elements with name: Entity and later I want to go through all of them and get values from their descendants with name "Reason".
But non of the Entity elements is found with this line:
var entityList = xmlDoc.Descendants(nameSpace + "Entity").ToList();
This is a whole method I am using:
public static void GetIBANAndBicValuesFromXML(XDocument xmlDoc)
{
var reasons = new List<string>();
XNamespace nameSpace =
"https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/";
var entityList = xmlDoc.Descendants(nameSpace + "Entity").ToList();
if (entityList != null)
{
foreach (var reason in entityList.Select(entity => entity.Elements(nameSpace + "Reason"))
.Where(reasonsList => reasonsList != null).SelectMany(reasonsList => reasonsList))
{
string reasonValue = reason.Value;
reasons.Add(reasonValue);
}
}
}
And this is a call to this method:
private static void Main(string[] args)
{
var xmlFile = "C:\\temp\\indi2.xml";
var x = XDocument.Load("C:\\temp\\Individuals.xml");
XMLParse.GetIBANAndBicValuesFromXML(x);
}
I have tried namespace like this as well:
"https://support.bridgerinsight.lexisnexis.com/downloads/xsd/4.5/OutputFile.xsd"
But no success.
Anybody sees what I am doing wrongly?
You can use Linq to filter with LocalName:
string fileName = "1.txt";
var xDoc = XDocument.Load(fileName);
var neededElements = xDoc.Descendants().Where(x => x.Name.LocalName == "Entity");
Console.WriteLine("Found {0} Entitys", neededElements.Count());
foreach(var el in neededElements)
{
Console.WriteLine(el);
}
There are some fields on my xml document which are same value but under different name. I want to select the value of "Error" on this xml document and so want to display "deger2". Also I want to display "deger5" How can I do this?
<?xml version="1.0" encoding="UTF-8"?>
<Database xmlns="http://www.example.com/2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Datas>
<Data name="sMsg" access="private" xsi:type="collection" type="string">
<Value key="Cycle" value="deger1" />
<Value key="Error" value="deger2" />
<Value key="Info" value="deger3" />
<Value key="Jog" />
<Value key="Warning" />
</Data>
<Data name="tTabla" access="private" xsi:type="array" type="tabla" size="1">
<Value key="Cycle" value="deger4" />
<Value key="Error" value="deger5" />
<Value key="Info" value="deger6" />
<Value key="Jog" />
<Value key="Warning" />
</Data>
</Datas>
</Database>
You should take the xml namespace into considiration. Using Linq to Xml
var xDoc = XDocument.Parse(xmlstring); //XDocument.Load(filename)
XNamespace ns = "http://www.example.com/2";
var errors = xDoc.Descendants(ns + "Value") //<-- See the usage of ns
.Where(d => (string)d.Attribute("key") == "Error")
.Select(d => (string)d.Attribute("value"))
.ToList();
EDIT
Is there any way to select like this: select error value where Data name="tTabla"?
var errors = xDoc.Descendants(ns + "Data")
.First(d => (string)d.Attribute("name") == "tTabla")
.Descendants(ns + "Value")
.First(d => (string)d.Attribute("key") == "Error")
.Attribute("value")
.Value;
EDIT2
You can also use XPATH
var nsmgr = new XmlNamespaceManager(xDoc.CreateNavigator().NameTable);
nsmgr.AddNamespace("ns", "http://www.example.com/2");
var errors = xDoc.XPathSelectElement("//ns:Data[#name='tTabla']/ns:Value[#key='Error']", nsmgr)
.Attribute("value")
.Value;
U can also use XPath to select them:
XmlNodeList nodeList = root.SelectNodes("//Data/Value[#key="Error"]");
I have a xml document like this and I need to access the "employees", "employee" elements so I am trying to use linq's XDocument class to get the employee elements but it always returns empty value.
Sample xml:
<organization>
<metadata>
</metadata>
<main>
<otherInfo>
</otherInfo>
<employeeInfo>
<employees>
<employee>
<id>1</id>
<name>ABC</name>
</employee>
<employee>
<id>2</id>
<name>ASE</name>
</employee>
<employee>
<id>3</id>
<name>XYZ</name>
</employee>
</employees>
</employeeInfo>
</main>
</organization>
C# code:
XDocument xDoc = XDocument.Parse(xmlString);
var allEmployees = from d in xDoc.Descendants("employeeInfo")
from ms in d.Elements("employees")
from m in ms.Elements("employee")
select m;
It kind of depends on what information you need. Your select returns an IEnumerable list.
This code will print out each employee
string xmlString = #"<organization>
<metadata>
</metadata>
<main>
<otherInfo>
</otherInfo>
<employeeInfo>
<employees>
<employee>
<id>1</id>
<name>ABC</name>
</employee>
<employee>
<id>2</id>
<name>ASE</name>
</employee>
<employee>
<id>3</id>
<name>XYZ</name>
</employee>
</employees>
</employeeInfo>
</main>
</organization>";
XDocument xDoc = XDocument.Parse(xmlString);
var allEmployees = from d in xDoc.Descendants("employeeInfo")
from ms in d.Elements("employees")
from m in ms.Elements("employee")
select m;
foreach (var emp in allEmployees) {
Console.WriteLine(emp);
}
Console.Read();
XDocument xDoc = XDocument.Parse(xmlString);
var allEmployees = (from r in xDoc.Descendants("employee")
select new
{
Id = r.Element("id").Value,
Name = r.Element("name").Value
}).ToList();
foreach (var r in allEmployees)
{
Console.WriteLine(r.Id + " " + r.Name);
}
Just use Descendants("Employee");
XDocument xDoc = XDocument.Parse(xmlString);
var allEmployees = xDoc.Descendants("employee").ToList();
i have xml document like this:
<?xml version="1.0" encoding="utf-8" ?>
<demographics>
<country id="1" value="USA">
<state id ="1" value="California">
<city>Long Beach</city>
<city>Los Angeles</city>
<city>San Diego</city>
</state>
<state id ="2" value="Arizona">
<city>Tucson</city>
<city>Phoenix</city>
<city>Tempe</city>
</state>
</country>
<country id="2" value="Mexico">
<state id ="1" value="Baja California">
<city>Tijuana</city>
<city>Rosarito</city>
</state>
</country>
</demographics>
How to select everything starting from demographics node using XML linq queries
something like this:
var node=from c in xmldocument.Descendants("demographics") ??
XDocument xDoc = XDocument.Parse(xml);
var demographics = xDoc
.Descendants("country")
.Select(c => new
{
Country = c.Attribute("value").Value,
Id = c.Attribute("id").Value,
States = c.Descendants("state")
.Select(s => new
{
State = s.Attribute("value").Value,
Id = s.Attribute("id").Value,
Cities = s.Descendants("city").Select(x => x.Value).ToList()
})
.ToList()
})
.ToList();
I wonder how do I parse a specific person by the id in the xml below?
Also lets say I wanna loop through them all and add them to a listview, How do I do that with XmlDocument?
<users>
<user id="Marcus">
<website>www.google.com</website>
<type>1</type>
</user>
<user id="John">
<website>www.youtube.com</website>
<type>1</type>
</user>
<user id="Josh">
<website>www.google.com</website>
<type>2</type>
</user>
</users>
Here's a linq to xml example -
using System.Xml.Linq;
var doc = XDocument.Parse(#"...");
var element = doc.XPathSelectElement("/users/user[#id='John']");
var website = element.XPathSelectElement("website").Value;
var type = int.Parse(element.XPathSelectElement("type").Value);