问题
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