This is my XML schema,
<Modules>
<Module name="Sales" path="../SalesInfo.xml" isEnabled="true" ... >
..............
</Module>
<Module name="Purchase" path="../PurchaseInfo.xml" isEnabled="true" ... >
..............
</Module>
................
</Module>
</Modules>
SalesInfo.XML
<Screens>
<Screen name="SalesOrder" ........ />
</Screen>
public class Module
{
public string Name
{
get;
set;
}
public string Type
{
get;
set;
}
.....
}
Here the modules and Screens are loaded on Request basis ("On Demand"). So i have to find the particular node when request comes(may be from menu click). Once the node is picked, it need to be converted to particular class. Eg when "sales" request comes, it should picked from XML and that need to converted to "Module" class. As one possible way is
- Using XPathNavigator and find the Node.
- Parse the "Finded Node" and convert to Particular class
This is bit complicated. I have to take care of all the attribute and its datatypes.
What i looking for
- Find the Node
- Convert the Node to My custom Class (I doesn't want to write code for Parser)
What is the Best approach. I'm working on C# 4.0.
EDIT:
XDocument document = XDocument.Load(path);
XElement mod = document.XPathSelectElement("Modules/Module[@name='PurchaseEnquiry']") as XElement;
Module purchaseModule = mod as Module; //This won't work, but i开发者_JS百科 want like this.
Well... Not entirely sure what you are looking for here but I'll give it a shot.
You could read the content node by node and deserialize each node to your class like this:
public class XmlDataReader<T> : IEnumerable, IDisposable
{
private readonly XmlTextReader reader = null;
public XmlDataReader(string filename)
{
reader = new XmlTextReader(filename) {WhitespaceHandling = WhitespaceHandling.None};
reader.MoveToContent(); // Go to root node.
reader.Read(); // Go to first child node.
}
#region Implementation of IEnumerable
public IEnumerator GetEnumerator()
{
if (reader == null) yield break;
do
{
var ser = new XmlSerializer(typeof (T));
var subTree = reader.ReadSubtree();
subTree.MoveToContent();
var node = ser.Deserialize(subTree);
subTree.Close();
yield return node;
reader.Skip();
} while (!reader.EOF && reader.IsStartElement());
}
#endregion
#region Implementation of IDisposable
public void Dispose()
{
if (reader != null)
reader.Close();
}
#endregion
}
In your case you could use it like this:
var reader = new XmlDataReader<Module>("data.xml");
foreach (Module node in reader)
{
...
}
精彩评论