Creating an Entity from XML

只谈情不闲聊 提交于 2019-12-24 05:17:06

问题


I have the following XML structure

<T>
 <F>
  <H>
   <H1>some value</H1>
   <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


回答1:


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.




回答2:


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.




回答3:


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;



来源:https://stackoverflow.com/questions/5938876/creating-an-entity-from-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!