0

I'm sure all the pros out there would find this very trivial but I need a quick solution for this in C#

I'm retrieving an xml schema of a view in share point which looks like this:

<FieldRef Name="LinkTitle"/><FieldRef Name="Author0"/><FieldRef Name="ID"/>

I want to parse this and only retrieve the Name's of each root element in this schema. currently this is the code I'm working on , need some help with it

String fieldvals = view.ViewFields.SchemaXml.ToString();
XmlDocument reader = new XmlDocument(); ;
reader.LoadXml(fieldvals);
String xpath = "/";
var nodes = reader.SelectNodes(xpath);

foreach (XmlNode childrenNode in nodes)
{
    Console.WriteLine(childrenNode.SelectSingleNode("//field1").Value);
}

Apparently, when this piece of code executes, I get an exception saying that more than one root node is present which is true of course .. but I'm not able to figure out the correct code to access every root node and extract it's name!

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
Aman Gupta
  • 7,883
  • 5
  • 16
  • 24
  • 2
    Ideally XML should have only one root node. You can wrap it in root node and then read all children at level 1 `` – Durgesh Chaudhary May 05 '14 at 09:00
  • 2
    I think the issue is that an XML document isn't allowed to have more than one root node. You need to wrap the `FieldRef` elements into an extra, surrounding element (e.e. `FieldRefs`). – Medo42 May 05 '14 at 09:00
  • Alright! Got it, Can wrap the nodes in a parent node. But, please can you show me the correct code that i can use to then access these nodes as the children of the parent node? I'd really appreciate it! – Aman Gupta May 05 '14 at 09:07
  • wrapped it up in a parent div called FieldRefs, however now I'm getting an new exception message saying that object reference is not set to an instance of an object – Aman Gupta May 05 '14 at 09:11
  • Try answer I posted it should work – Durgesh Chaudhary May 05 '14 at 09:13

2 Answers2

2

Wrap your xml fragment within a root node and then you can use linq to xml to retrieve a string array of those names like this:

var xml = XElement.Parse(xmlString);
var names=xml.Elements().Attributes(@"Name").Select(attrib => attrib.Value);
Victor Mukherjee
  • 10,487
  • 16
  • 54
  • 97
0

You should wrap your xml in some root node as an XML can have only one Root Node as below :

<FieldRefs>
    <FieldRef Name="LinkTitle"/>
    <FieldRef Name="Author0"/>
    <FieldRef Name="ID"/>
</FieldRefs>

And then your code will execute fine.

String fieldvals = view.ViewFields.SchemaXml.ToString();
XmlDocument reader = new XmlDocument(); ;
reader.LoadXml(fieldvals);
String xpath = "/FieldRefs/FieldRef";
var nodes = reader.SelectNodes(xpath);

foreach (XmlNode childrenNode in nodes)
{
    /*Process here*/
}
Durgesh Chaudhary
  • 1,075
  • 2
  • 12
  • 31