简体   繁体   中英

How to properly model an XML node with Attributes?

I'm trying to consume an XML feed and convert it into a model.

Some of the XML looks like this.

<guid isPermaLink="false">
    http://example.com/foo/bar
</guid>

In trying to model this, I'm using

[XmlElement("guid")]
public string Guid { get; set; }

[XmlElement("guid")]
public m_Guid Guid { get; set; }
public class m_Guid
{
    [XmlAttribute("isPermaLink")]
    public bool isPermaLink { get; set; }
}

but obviously VS is throwing an error

This member is defined more than once.

I'm simply trying to figure out how to model this so that at the end of it all, I can use

var theGuid = someItem.Guid;
var guidIsPermaLink = someItem.Guid.isPermaLink;

Just hoping someone can help point me in the right direction. I'm kind of new to modeling like this.


Here's another example of confusing markup that needs to be modeled in a similar way.

<link>http://example.com/foo/bar/</link>
<atom:link rel="self" type="application/rss+xml" href="http://example.com/foo/bar/&format=rss"/>

needs to be modeled so that we can do this

var link = someItem.Link;
var linkType = someItem.Link.type;
var linkHref = someItem.Link.href;

You could model it like this:

public class Guid 
{
    [XmlAttribute]
    public bool IsPermaLink { get; set; }

    // and the element value
    [XmlTextAttribute]
    public string Value;
}

public class Item
{
    [XmlElement]
    public Guid Guid { get; set; }
}
...
var theGuid = someItem.Guid.Value;
var guidIsPermaLink = someItem.Guid.IsPermaLink;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM