1

Possible Duplicate:
C#: Read XML Attribute using XmlDocument

In C# if I were to have the XMLDocument containing:

<Hello>
<Person:"Alan" Saying:"My name is Alan">
</Hello>

Then how might I obtain the single attribute "Saying"? I've found code which works when a single attribute is contained within the "<>" however it does not appear to work where there are multiple attributes inside as is above.

Any help would be much appreciated, I'm rather a C# novice :)

Community
  • 1
  • 1
IApp
  • 667
  • 1
  • 6
  • 18

2 Answers2

4

First off, that is not valid xml. I think you want something like

<Hello>
    <Person name="Alan" Saying="My name is Alan" />
</Hello>

and the simplest way to get Alan's Saying is

XmlDocument doc = new XmlDocument();
doc.Load("filename.xml");
string saying = doc.SelectSingleNode("//Person[@name=Alan]").Attributes["saying"].Value;

for a more detailed explanation of why that works, see XPath Examples

1

Your XML should be:

<Hello>
    <Person name="Alan" saying="My name is Alan"/>
</Hello>

Your class to deserialize this would be:

public class Hello
{
    public Person Person { get; set; }
}

public class Person
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlAttribute]
    public string Saying { get; set; }
}

How to use it:

// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(Hello));

// load xml into string reader
StringReader reader = new StringReader(yourXmlString);

// Load the object saved above by using the Deserialize function
Hello LoadedObj = (Hello)SerializerObj.Deserialize(reader);

Check out the MSDN article for more info on how to use the XmlSerializer

Steve Konves
  • 2,648
  • 3
  • 25
  • 44