I've got a problem with XML unit Testing.
Basically the problem is that there are 2 identical tags under same xpath, and I don't really know how exactly I should compare all of the children inside
...aperson...
.../aperson...
if there is another one identical, but with (different values inside)
Samples are made in list and my guess is i need to make both <aperson> </aperson> from XML Document in to list as well, but I'm not too sure about it and don't really have an idea how to do it.
<Person>
<apersons>
<aperson>
<person_name></person_name>
<person_code></person_code>
<institut></institut>
<post></post>
<rep_type></rep_type>
<persreg></persreg
<state></state>
<address/>
</aperson>
<aperson>
<person_name></person_name>
<person_code></person_code>
<institut></institut>
<post></post>
<rep_type></rep_type>
<persreg></persreg>
<state></state>
<address/>
</aperson>
</apersons>
</person>
C#
c.Personas.Add(new Person
{
Name = "Elga",
Code = "-10317",
Institut = "Valde",
Post = "loceklis",
RepType = "1",
Perseg = "-07-03",
State = "LV"
});
// Person2
c.Personas.Add(new Person
{
Name = "Elga1",
Code = "-10317",
Institut = "Valde",
Post = "loceklis",
RepType = "1",
Perseg = "-07-03",
State = "LV"
});
CODE: pastebin
Related
I have got a file called xmlfile.xml:
<Personen>
<Person>
<Vorname>Manfred</Vorname>
<Telefon/>
<Zuname>Fischer</Zuname>
<Alter>45</Alter>
<Adresse Ort="Bonn" Strasse="Neuestr.34"></Adresse>
</Person>
</Personen>
There are two problems. First of all are the fields of '' variable. So maybe the xmlfile contains 3 persons or another value (of course it contains at least one). Now I need to print out the 'Vorname' of each Person, how can I do so? I tried this code (just a short view):
reader.ReadToFollowing("Person");
string isbn = reader.GetAttribute("Alter");
Console.WriteLine("age: " + isbn);
Console.ReadLine();
But it doesn't print out the age (Alter), how to get it working to print out the age of each person, in case there are more then one.
Just do a quick search and you'll find plenty of resource to read XML via fabulous Linq:
LINQ to read XML
For example to extract persons:
XDocument xdoc = XDocument.Load(yourFileName));
var persons = from lv1 in xdoc.Descendants("Person")
select lv1.Value;
I know basic about getting node values from a xml file, but in a complicated xaml file I don't know how to write my linq query.
This is a sample of xaml I'm using:
<Activity something:something = " 2010" x:class = "example"..........>
<x:Members>
<x:Property Name= "aaaaa" Type = "Inargument" />
</x:Members>
<sap:abcdef>1322,2222</sap:abcdef>
<prwab:work sap2010:Annotation.AnnotationText = " I need this value" Active = "False" CreatedOn = "2014-07-09" ID = "123456" DisplayName = "theNameIneed">
<prwab:work.activity>
<prwais:collectingActivity sap2010:Annotation.AnnotationText = "I also need this value" > CreatedOn = "2014-07-09" ID = "1234232" DisplayName = "Ineed2">
<prwais .....>
</prwais>
</prwis:collectingActivity>
</prwab:work.activity>
</prwab:work>
</Activity>
I need to get the data in the lines that contain attribute "sap2010:Annotation.AnnotationText", and the value is going to be the content of sap2010:Annotation.AnnotationText, and key is going to be the attribute "ID" and attribute "displayName" in that line.
Here is the query I have right now, I know it's wrong but I don't know the proper way to write it:
var dataNodes = XElement.Load(file, LoadOptions.None);
Console.WriteLine("Loaded xaml file: " + file);
var dataNodesDictionary = from dataRecord in (dataNodes.Elements("prwab") && dataNodes.Elements("prwais"))//this line is wrong, but I dont know how to write it, since annotation may appears in different elements, and even if I only use "prwab" for testing, i still get nothing
where dataRecord.Attributes("Annotation.AnnotationText") != null
select new DictionaryEntry
{
Key = dataRecord.Attribute("DisplayName").Value.ToString() + "|" + dataRecord.Attribute("ID").Value.ToString(),
Value = dataRecord.Attribute("Annotation.AnnotationText").Value.ToString(),
};
Can some one help me please, thanks.
First find all elements that have the attribute. Then pull the attribute values.
// Name of the attributes we are looking
string ns = "http://schemas.microsoft.com/netfx/2010/xaml/activities/presentation";
XName name = XName.Get("Annotation.AnnotationText", ns);
XDocument doc = XDocument.Load("XMLFile1.xml");
var q = doc.Descendants().Where(e => e.Attribute(name) != null)
.Select(e => new DictionaryEntry { Key = e.Attribute("ID").Value, Value = e.Attribute(name).Value });
SIDE NOTE: In the future please paste in valid XML so it is easier for others to reproduce the issue.
Since this is XAML, you'll have a problem:
The attribute you're looking for can be written using a tag:
<prwab:work sap2010:Annotation.AnnotationText="I need this value">
...
</prwab:work>
This is equivalent to:
<prwab:work>
<sap2010:Annotation.AnnotationText>
I need this value
</sap2010:Annotation.AnnotationText>
...
</prwab:work>
So if you need a reliable way to read that, you should use the XamlReader class (the one from the System.Xaml namespace - not the one from System.Windows.Markup). It works in a similar way to XmlReader, but normalizes the XAML it presents to you.
It won't be as straightforward as a linq query, but will be more reliable.
I try to parse this XML weather info into my application.
<weather>
<date>2014-01-03
</date>
<chanceofsnow>0</chanceofsnow>
<totalSnowfall_cm>0.0</totalSnowfall_cm>
<top>
<maxtempC>-3</maxtempC>
<maxtempF>27</maxtempF>
<mintempC>-5</mintempC>
<mintempF>24</mintempF>
</top>
<hourly>
<time>100</time>
<top>
<tempC>-6</tempC>
<tempF>20</tempF>
<windspeedMiles>8</windspeedMiles>
<windspeedKmph>13</windspeedKmph>
<winddirDegree>213</winddirDegree>
<winddir16Point>SSW</winddir16Point>
<weatherCode>113</weatherCode>
<weatherIconUrl><![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png]]> </weatherIconUrl>
<weatherDesc><![CDATA[Clear]]></weatherDesc>
</top>
</hourly>
</weather>
I use the following C# to parse it:
XElement XmlSneeuw = XElement.Parse(e.Result);
//current
listBoxVandaag.ItemsSource
= from weather in XmlSneeuw.Descendants("weather")
select new AlgemeneInformatie
{
Chance_of_Snow = weather.Element("chanceofsnow").Value,
Total_Snowfall = weather.Element("totalSnowfall_cm").Value,
};
//Current
listBoxVandaagTop.ItemsSource
= from weather1 in XmlSneeuw.Descendants("top")
select new AlgemeneInformatieTop
{
Actueel_Top_maxtempC = weather1.Element("maxtempC").Value,
Actueel_Top_mintempC = weather1.Element("mintempC").Value,
};
But now there are 2 TOP elements in my xml so this wont work. what is the best way to do this? and is this the right method to parse this kind of information?
I used this site as a reference:
http://developer.nokia.com/Community/Wiki/Weather_Online_app_for_Windows_Phone
I would suggest querying the XML using LINQ and XPath, example here
//...
var topElement = XmlSneeuw.XPathSelectElement("./weather/top")
//Create your min/max object
//...
you can use .Elements("top") as below, that limit the sub level elements with same name
listBoxVandaagTop.ItemsSource = XmlSneeuw.Elements("top").Select( weather1=> new AlgemeneInformatieTop
{
Actueel_Top_maxtempC = weather1.Element("maxtempC").Value,
Actueel_Top_mintempC = weather1.Element("mintempC").Value,
});
Hi there I'm trying to parse an XML file into a list of contacts, but having problems:
public List<ContactModel> GetContacts()
{
var doc = XDocument.Load(HttpContext.Current
.Server
.MapPath(#"..\App_Data\Contacts.xml"));
var result = from items in doc.Descendants("Directory")
select new ContactModel()
{
Id = items.Attribute("ID").Value,
FirstName = items.Attribute("FirstName").Value,
LastName = items.Attribute("LastName").Value,
Telephone = items.Attribute("Telephone").Value,
Email = items.Attribute("Email").Value,
Room = items.Attribute("Room").Value,
Building = items.Attribute("Building").Value,
Location = items.Attribute("Location").Value
};
List<ContactModel> contactList = new List<ContactModel>();
foreach (var item in result)
{
contactList.Add(item);
}
return contactList;
}
I get a null exception when it's trying to loop, what am I doing wrong?
This is my XML
<?xml version="1.0" standalone="yes"?>
<ContactDirectory>
<Directory>
<ID>1</ID>
<FirstName>Peter</FirstName>
<LastName>Sutt</LastName>
<Telephone>777888</Telephone>
<Email>pett#gmail.com</Email>
<Room>3.44</Room>
<Building>Westside</Building>
<Location>Leeds</Location>
</Directory>
<Directory>
<ID>2</ID>
<FirstName>Fred</FirstName>
<LastName>West</LastName>
<Telephone>1234</Telephone>
<Email>fred#west.com</Email>
<Room>1.23</Room>
<Building>Cromwell St</Building>
<Location>Gloster</Location>
</Directory>
<Directory>
</ContactDirectory>
Beebul, They are Elements not Attributes
var contactList = (from items in doc.Descendants("Directory")
select new ContactModel()
{
Id = items.Element("ID").Value,
FirstName = items.Element("FirstName").Value,
LastName = items.Element("LastName").Value,
Telephone = items.Element("Telephone").Value,
Email = items.Element("Email").Value,
Room = items.Element("Room").Value,
Building = items.Element("Building").Value,
Location = items.Element("Location").Value
})
.ToList();
PS: you don't need to loop over your result to get a list. You can use ToList()
It looks like one or more of your attributes are missing. items.Attribute(...) returns null, and calling Value on it causes the NPE*.
Since the execution is deferred, the call does not happen until you start looping through the result.
To find the attribute that causes the problem remove all calls to Attribute(...) except for ID, verify that the crash does not happen, and start adding back the attributes one by one until the crash is back.
* After seeing the XML that you added to your question it appears that all attributes are missing! Here is a link to a short article that discusses the differences.
The Linq to XML API has implicit conversions to help with possible null references returned from .Value. Try something like (string) items.Attribute("Room").
I can't figure out why my code just taking the first tag and not the rest.
var xml = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/Themes.xml"));
var q = from f in xml.Descendants("themes")
select new ThemesItem
{
Name = f.Element("theme").Element("name").Value,
Description = f.Element("theme").Element("description").Value,
Author = f.Element("theme").Element("author").Value,
};
return q.ToList();
ThemeItem is just a get set with public string
When i write out this data i use a repeater
Thanks for help :)
That is because the Descendants extension method takes all decendants of the xml node, that is named "themes". Since your themes node is the container for the individual theme tags, there is only one, and when you take .Element on that, you get the first occurence.
This code should work:
var q = from f in xml.Descendants("theme")
select new ThemesItem
{
Name = f.Element("name").Value,
Description = f.Element("description").Value,
Author = f.Element("author").Value,
};
<themes>
<theme>
<name>Standard</name>
<description>standard theme</description>
<author>User 1</author>
<folder>standard</folder>
</theme>
<theme>
<name>Standard</name>
<description>standard theme</description>
<author>User 2</author>
<folder>standard</folder>
</theme>
</themes>
Try using XElement.Load() instead of XDocument.Load()
http://msdn.microsoft.com/en-us/library/bb675196.aspx