使用XPathNavigator读取XML中的根属性 [英] reading root attribute in a XML using XPathNavigator

查看:95
本文介绍了使用XPathNavigator读取XML中的根属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是使用XPathNavigator并尝试读取root中存在的属性的新手。在下面的示例中,它是AppPlatformVersion。我需要在C#中使用XPathNavigator读取值8.0

I am a new bie to using XPathNavigator and trying to read attribute present in the root. In the below example, it is AppPlatformVersion. I need to read the value 8.0 using XPathNavigator in C#

XPathDocument d = new XPathDocument(reader);
XPathNavigator n = d.CreateNavigator;


 

 < Deployment xmlns =" http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion = QUOT; 8.0"> < / Deployment>

 

 <Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0"> </Deployment>

任何人都可以帮助如何使用C#提取root属性吗?

Can any one help how to extract the root attribute using C#?

谢谢

Sahasra

推荐答案

你可以这样做:

You can do it like this:

namespace UsingXPathNavigator
{
    using System;
    using System.IO;
    using System.Xml;
    using System.Xml.XPath;

    internal static class Program
    {
        private static void Main()
        {
            string xml = "<Deployment xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\" AppPlatformVersion=\"8.0\"> </Deployment>";

            XPathDocument d;
            using (StringReader reader = new StringReader(xml))
            {
                d = new XPathDocument(reader);
            }

            XPathNavigator n = d.CreateNavigator();
            n.MoveToChild(XPathNodeType.Element); // will succeed because any XML document has a root element
            string attribute = n.GetAttribute("AppPlatformVersion", string.Empty);
            if (attribute != null)
            {
                Console.WriteLine(attribute);
            }
        }
    }
}

但是,如果你必须检查深度XML,XPathNavigator会很烦人结构体;很容易意外地让导航器指向错误的节点。  System.Xml.Linq对我来说更方便。

However, XPathNavigator is rather annoying to use if you have to examine a deep XML structure; it is easy to accidentally leave the navigator pointing to the wrong node.  System.Xml.Linq feels more convenient to me.

namespace UsingLinqToXml
{
    using System;
    using System.Xml.Linq;

    internal static class Program
    {
        private static void Main()
        {
            string xml = "<Deployment xmlns=\"http://schemas.microsoft.com/windowsphone/2012/deployment\" AppPlatformVersion=\"8.0\"> </Deployment>";

            XDocument d = XDocument.Parse(xml);

            string attribute = (string)d.Root.Attribute("AppPlatformVersion");
            if (attribute != null)
            {
                Console.WriteLine(attribute);
            }
        }
    }
}


这篇关于使用XPathNavigator读取XML中的根属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆