开发者

Creating an Entity from XML

I have the following XML structure

<T>
 <F>
  <H>
   <H1>some value</H1>
   &开发者_开发问答lt;H2>some value</H2>
   <H3>some value</H3>
  </H>
  <O>
   <P>some value</P>
   <TI>some value</TI>
   <TI>some value</TI>
  </O>
  <R>
   <PTY>some value</PTY>
   <PTY>some value</PTY>
   <PTY>some value</PTY>
  </R>
 </F>
<T>  

I need to parse this xml in C# and get the values out of them to be further exported to a CSV file. My query is how do you go about creating an entity for this XML


You can play with XmlSerializer and its related attributes.

As long as the XML is not too complex, there's not much work to do.

To read the XML:

var serializer = new XmlSerializer(typeof(SerializableObject));

SerializableObject deserialized;

using (var stream = new FileStream(@"C:\test.xml", FileMode.Open))
{ 
    deserialized = (SerializableObject)serializer.Deserialize(stream);
}

The SerializableObject will look like this:

[Serializable]
[XmlRootAttribute("T")]
public class SerializableObject
{
    ...
}

BONUS for lazy programmers: You can just use Xsd.exe to brute force create an object from an XML file. Then tweak the results to your needs.


You can use LinqToXml to parse xml. StringBuilder will be helpful to produce CSV.

I think these How Tos will be useful. They describe all you needed to parse this xml.


add using System.Xml.Linq; then you can do something similar to this:

XDocument xml = XDocument.Load(@"....\People.xml"); var query = from p in xml.Elements("people").Elements("person") where (int)p.Element("id") == 1 select p;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜