83180

Reading dynamic elements from the xml file using c#`

Question:

I want to read the xml elements dynamically (I mean without hard-coding the element name) from the xml file. I am not able to use the XmlReader.ReadToDescendant method as it expects a Local Name which in my case varies. For example in this case I need to read elements A, B, C, D & etc...

<?xml version="1.0" encoding="UTF-8"?> <test Version="2010" xmlns="http://test.org/2010/values"> <A> <Data> <Somedata></Somedata> </Data> <Rows> <Row></Row> <Row></Row> </Rows> </A> <B> <Data> <Somedata></Somedata> </Data> <Rows> <Row></Row> <Row></Row> </Rows> </B> <C> <Data> <Somedata></Somedata> </Data> <Rows> <Row></Row> <Row></Row> </Rows> </C> <D> <Data> <Somedata></Somedata> </Data> <Rows> <Row></Row> <Row></Row> </Rows> </D> </test>

Please help me.

Answer1:

That's pretty simple:

XDocument doc = XDocument.Load("test.xml"); string name = GetNameFromWherever(); foreach (XElement match in doc.Descendants(name)) { ... }

That's using LINQ to XML - a lovely API for XML if you're using .NET 3.5 or later... it's <em>much</em> nicer than using XmlReader.

Answer2:

For dynamic generation of XML content into another set of classes you could do something like this:

class GenericNode { private List<GenericNode> _Nodes = new List<GenericNode>(); private List<GenericKeyValue> _Attributes = new List<GenericKeyValue>(); public GenericNode(XElement Element) { this.Name = Element.Name; this._Nodes.AddRange(Element.Elements() .Select(e => New GenericNode(e)); this._Attributes.AddRange( Element.Attributes() .Select(a => New GenericKeyValue(a.Key, a.Value)) } public string Name { get; private set; } public IEnumerable<GenericNode> Nodes { get { return this._Nodes; } } public IEnumerable<GenericKeyValue> Attributes { get { return this._Attributes; } } } class GenericKeyValue { public GenericKeyValue(string Key, string Value) { this.Key = Key; this.Value = Value; } public string Key { get; set; } public string Value { get; set; } }

Then you simply:

XElement rootElement = XElement.Parse(StringOfXml); // or XElement rootElement = XElement.Load(FileOfXml); GenericNode rootNode = new GenericRode(rootElement);

Recommend

  • How to wait for multiple WebWorkers in a loop
  • window.open with target '_blank' opens a new browser window
  • ANOVA on multiple responses, by multiple groups NOT part of formula
  • Capturing range of lines with awk, multiline records not working
  • XSD with multi occurrences unordered
  • Splash Screen will not display
  • JBoss External Properties Files in Classpath
  • Android - Material Design - NavigationView - How to put vertical scroll?
  • Jquery UI tool tip close icon
  • ImageMagick, replace semi-transparent white with opaque white
  • Cannot connect to cassandra from Spark
  • Pass value from viewmodel to script in zk
  • Display issues when we change from one jquery mobile page to another in firefox
  • Deselecting radio buttons while keeping the View Model in synch
  • Uncaught Error: Could not find module `ember-load-initializers`
  • Cross-Platform Protobuf Serialization
  • SSO with signing and signature validation doesn't work
  • Deserializing XML into class C#
  • JSON with duplicate key names losing information when parsed
  • Convert array of 8 bytes to signed long in C++
  • Alternatives to the OPTIONAL fallback SPARQL pattern?
  • Jquery - Jquery Wysiwyg return html as a string
  • bootstrap to use multiple ng-app
  • How to get icons for entities from eclipse?
  • How to include full .NET prerequisite for Wix Burn installer
  • Understanding cpu registers
  • embed rChart in Markdown
  • Turn off referential integrity in Derby? is it possible?
  • JaxB to read class hierarchy
  • Recursive/Hierarchical Query Using Postgres
  • Running Map reduces the dimensions of the matrices
  • How to get NHibernate ISession to cache entity not retrieved by primary key
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • Unable to use reactive element in my shiny app
  • Conditional In-Line CSS for IE and Others?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize