【问题标题】:Get xml node using c#使用c#获取xml节点
【发布时间】:2012-04-03 13:12:02
【问题描述】:

我有一个返回大型 xml 文件的请求。我的应用程序中有 XmlDocument 类型的文件。从那个文档我怎么能读到这样的元素:

<gphoto:videostatus>final</gphoto:videostatus>

我想从该元素中提取最终值。另外,如果我也有多个元素,我可以将其拉入列表吗?感谢您的建议。

【问题讨论】:

  • 这就是您想要的 XML 文件吗?只有gphoto:videostatus 元素?
  • @RobertHarvey,是的,这就是我想要的一件事。而且我还想提取具有相同“元素名称”的元素列表,例如 link1link2>
  • @gideon 我没有尝试太多。我现在正在网上搜索信息。
  • 显然,您的 XML 定义了 XML 命名空间 (gphoto) - 您需要查看XmlNamespaceManager,了解如何定义 XML 命名空间来解析您的 XML 文档。

标签: c# xml


【解决方案1】:

如果您已经有一个 XmlDocument,那么您可以使用函数 GetElementsByTagName() 创建一个可以类似于数组访问的 XmlNodeList。

http://msdn.microsoft.com/en-us/library/dc0c9ekk.aspx

//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load("books.xml");

//Display all the book titles.
XmlNodeList elemList = doc.GetElementsByTagName("title");
for (int i=0; i < elemList.Count; i++)
{   
  Console.WriteLine(elemList[i].InnerXml);
} 

【讨论】:

    【解决方案2】:

    您可以使用 XPath 和 SelectSingleNode SelectNodes 选择节点。查看http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C 的示例。然后你可以使用例如 InnerText 来获得最终结果。也许您需要使用命名空间 (gphoto)。 //videostatus 将选择所有 videostatus 元素

    【讨论】:

      【解决方案3】:

      您可以尝试使用 LINQ

              XNamespace ns = XNamespace.Get(""); //use the xmnls namespace here
              XElement element = XElement.Load(""); // xml file path
              var result = element.Descendants(ns + "videostatus")
                           .Select(o =>o.Value).ToList();
      
             foreach(var values in value)
             {
      
             }           
      

      谢谢

      深浦

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-03
        • 2013-08-12
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        相关资源
        最近更新 更多