Convert xml tag to anonymous type
I was looking to convert an xml file I had to return me a list of anonymous types so I have somethings like this:
<Input name="MyProperty" datatype="string">a</Input>
<Input name="SecondProperty" datatype="IPAddress">b</Input>
<Input name="ThirdProperty" datatype="int">c</Input>
and wanted it to be converted into a format as below:
select new
开发者_StackOverflow {
MyProperty=a,
SecondProperty=b,
ThridProperty=c,
}
Would it be possible to do this?The idea is to return a list of those inputs to feed into
another method.Also anything wrong doing things this way?thanks any help is appreciated
If you know in advance the name of the properties, you can do that:
XElement doc = ...
var obj = new
{
MyProperty = doc.Root.Elements("Input").First(e => e.Attribute("name") == "MyProperty").Value,
SecondProperty = doc.Root.Elements("Input").First(e => e.Attribute("name") == "SecondProperty").Value,
ThirdProperty = doc.Root.Elements("Input").First(e => e.Attribute("name") == "ThirdProperty").Value
}
If you don't know the names, you can't use an anonymous type. Anonymous types are really normal types with no name, their members are declared statically.
May not be the solution your looking for but just wanted to through it out there...
Something I've found helpful when faced with XML is decorating a class with the Serializable attribute...it make serializing to and from XML a breeze. http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx You can further manipulate the output to get the XML format you need.
Edit to answer you answer your question about varying properties which may not be of interest but here is what could be done:
[Serializable]
public struct SerializableKeyValuePair<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
}
[Serializable]
public class Input
{
public List<SerializableKeyValuePair<string, string>> PropertyBag { get; set; }
}
However, you would not have as much control as all properties will need to be an attribute OR an element represented in XML.
精彩评论