Frage

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!

War es hilfreich?

Lösung

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);

Andere Tipps

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*/
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top