简体   繁体   English

从XMLDocument中的xml文件读取节点

[英]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... 我试图抓住TopicName我应该如何去追求它并尝试不同的组合但不知何故我无法获得下面的TopicName是我的源代码...

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 示例xml文件

<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: XML中的Topic节点使用content命名空间 - 您需要在代码中声明并使用XML命名空间,然后您可以使用SelectNodes()来获取感兴趣的节点 - 这对我有用:

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: 正如比较一样,看看Linq对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: 如果你只需要一个特定的元素,那么我将使用XPath:

This is a guide to use XPath in C#: http://www.codeproject.com/KB/XML/usingXPathNavigator.aspx 这是在C#中使用XPath的指南: 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: 你可以根据你想要完成的内容调整这个查询,只获取一个特定的TopicName值:

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

XPath is pretty easy to learn. XPath很容易学习。 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: 您可以在此处粘贴XML和xpath查询以测试您的查询:

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

The following quick and dirty LINQ to XML code obtains your TopicNames and prints them on the console. 以下快速和脏的LINQ to XML代码获取您的TopicNames并在控制台上打印它们。

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). 如果它不适用于所有命名空间:)它会短得多(而不是“XName.Get”,你只需要使用元素的名称)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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