简体   繁体   中英

reading node from xml file in XMLDocument

i am trying to grab the TopicName how should i go after it and try different combination but somehow i am unable to get TopicName below is my source codee...

XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing

    xdoc.Load(
        "http://latestpackagingnews.blogspot.com/feeds/posts/default"
        );//loading XML in xml doc

    XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("content");//reading node so that we can traverse thorugh the XML

    foreach (XmlNode xNode in xNodelst)//traversing XML 
    {
        //litFeed.Text += "read";
    }

sample xml file

<content type="application/xml">
 <CatalogItems xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="sitename.xsd">
        <CatalogSource Acronym="ABC" OrganizationName="ABC Corporation" />
        <CatalogItem Id="3212" CatalogUrl="urlname">
          <ContentItem xmlns:content="sitename.xsd" TargetUrl="url">
            <content:SelectionSpec ClassList="" ElementList="" />
            <content:Language Value="eng" Scheme="ISO 639-2" />
            <content:Source Acronym="ABC" OrganizationName="ABC Corporation" />
            <content:Topics Scheme="ABC">
              <content:Topic TopicName="Marketing" />
              <content:Topic TopiccName="Coverage" />
            </content:Topics>
          </ContentItem>
        </CatalogItem>
      </CatalogItems>
    </content>

The Topic nodes in your XML are using the content namespace - you need to declare and use the XML namespace in your code, then you can use SelectNodes() to grab the nodes of interest - this worked for me:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);
nsmgr.AddNamespace("content", "sitename.xsd");

var topicNodes = xdoc.SelectNodes("//content:Topic", nsmgr);

foreach (XmlNode node in topicNodes)
{
    string topic = node.Attributes["TopicName"].Value;
}

Just as a comparison see how easy this would be with Linq to XML:

XDocument xdoc = XDocument.Load("test.xml");
XNamespace ns = "sitename.xsd";
string topic = xdoc.Descendants(ns + "Topic")
                   .Select(x => (string)x.Attribute("TopicName"))
                   .FirstOrDefault();

To get all topics you can replace the last statement with:

var topics = xdoc.Descendants(ns + "Topic")
                 .Select(x => (string)x.Attribute("TopicName"))
                 .ToList();

If you just need a specific element, then I'd use XPath:

This is a guide to use XPath in C#: http://www.codeproject.com/KB/XML/usingXPathNavigator.aspx

And this is the query that will get you a collection of your Topics:

//content/CatalogItems/CatalogItem/ContentItem/content:Topics/content:Topic

You could tweak this query depending on what it is you're trying to accomplish, grabbing just a specific TopicName value:

//content/CatalogItems/CatalogItem/ContentItem/content:Topics/content:Topic/@TopicName

XPath is pretty easy to learn. I've done stuff like this pretty quickly with no prior knowledge.

You can paste you XML and xpath query here to test your queries:

http://www.bit-101.com/xpath/

The following quick and dirty LINQ to XML code obtains your TopicNames and prints them on the console.

XDocument lDoc = XDocument.Load(lXmlDocUri);

foreach (var lElement in lDoc.Element("content").Element(XName.Get("CatalogItems", "sitename.xsd")).Elements(XName.Get("CatalogItem", "sitename.xsd")))
{
     foreach (var lContentTopic in lElement.Element(XName.Get("ContentItem", "sitename.xsd")).Element(XName.Get("Topics", "sitename.xsd")).Elements(XName.Get("Topic", "sitename.xsd")))
     {
           string lTitle = lContentTopic.Attribute("TopicName").Value;
           Console.WriteLine(lTitle);
     }
}

It'd have been a lot shorter if it wasn't for all the namespaces :) (Instead of "XName.Get" you would just use the name of the element).

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