Parsing XML in C#

I am still working on a project and I am enjoying it greatly.

I wanted to see if I could implement a live updating feed using XML

at the moment I dont even know how to parse this particular type of XML as all the tutorials I have found are for parsing node values etc

but I was thinking something along the lines of this

<Object name="ObjectName" type="ObjectType" size="ObjectSize" image="ObjectImage" />

if you guys could help me understand how to access the inner elements of from that node that would be amazing, and if it is not too much to ask just a small explanation so I understand. I know how to parse XML that looks like this using XElement

<Object>
    <Name>ObjectName</Name>
    <Type>ObjectType</Type>
    <Size>ObjectSize</Size>
    <Image>ObjectImage</Image>
</Object>

I just cant seem to parse the example at the top, I dont mind if its Linq as long as it is in C#, maybe tell me why you would chose one over the other? Also have you got any idea on how to perhaps check if the file has changed, so I could implement a live update?

Thanks for your Help

John

Upvotes: 0

Views: 291

Answers (3)

Anders Forsgren
Anders Forsgren

Reputation: 11101

If you have a domain object that represents your document (usually the case), then the XmlSerializer is quite easy to use.

[XmlRoot("Object")
public class Item
{
   public string Name { get; set; }
   public string Type { get; set; }
   public string Size { get; set; }
   public string Image { get; set; }
}

Usage:

XmlSerializer ser = new XmlSerializer(typeof(Item));
Item item = (Item)ser.Deserialize(someXmlStream);

I find using this approach easier than manual parsing when an entire document represents a domain object of some kind.

Upvotes: 3

ChrisF
ChrisF

Reputation: 137108

Use can also use XEelment.FirstAttribute to get the first attribute on the element and then XAttribute.NextAttribute to loop through them all. This doesn't rely on you knowing that the attribute is present.

XAttribute attribute = element.FirstAttribute;
while (attribute != null)
{
    // Do stuff
    attribute = attribute.NextAttribute`
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499730

The example at the top uses attributes instead of sub-elements but it's just as easy to work with:

XElement element = XElement.Parse(xml);
string name = (string) element.Attribute("name");
string type = (string) element.Attribute("type");
string size = (string) element.Attribute("size");
string image = (string) element.Attribute("image");

I usually prefer to use the explicit string conversion instead of the Value property as if you perform the conversion on a null reference, you just end up with a null string reference instead of a NullReferenceException. Of course, if it's a programming error for an attribute to be missing, then an exception is more appropriate and the Value property is fine. (The same logic applies to converting XElement values as well, by the way.)

Upvotes: 4

Related Questions