简体   繁体   中英

Retrieving xml value into a string

In the following XML structure how do i retrieve the name value and put this into a string? (i am using a XPathNavigator in my method)

<testsystem>
    <test>
       <name>one</name>
       <name>two</name>
       <name>three</name>
    </test>
</testsystem>

The name will get displayed in the boundcolumn of a datagrid.

I was able to get a attribute with a syntax alike this: (but when changing the xml struture it no longer holds a attribute value)

string name = nav.GetAttribute("name", "")

But have no luck getting the value with a nav as of yet.

The purpose is to be able to use it for the following object so i can put name into it.

test t = new test() { Name = name, Questions= new List<Questions>() };

Best regards.

For multiple name nodes you could use this approach:

XPathNodeIterator iter = xml.CreateNavigator().Select("//test/name");
while (iter.MoveNext())
{
    var nav = iter.Current;
    string name = nav.Value;
    Console.WriteLine(name);
}

Alternately you could use the XmlDocument.GetElementsByTagName method :

var nodeList = xml.GetElementsByTagName("name");
foreach (XmlNode node in nodeList)
{
    Console.WriteLine(node.InnerText);
}

For example, create an XmlDocument, load the string into it with the LoadXml method, and then document.GetElementsByTagName("name")[0].InnerText will provide the value. There may be better ways to deal with XML if we knew how complex your XML structure actually is.

Assuming the XPathNavigator is positioned on the element you want, than nav.Value will return the string value. See XPathItem.Value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM