提取XML文件内容 [英] Extract contents from XML file

查看:192
本文介绍了提取XML文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用一个按钮来生成一个文件C#应用程序。目前,我想用C#从XML文件中提取出来的内容,并将其作为一个字符串传递。例如,在我的XML文件中,我有一个标签名。我想用C#从XML文件中提取的名字。我应该如何去实现呢?下面是示例代码我现在有。整个过程中必须使用一个按钮点击来进行。

I have a C# application that uses a button to generate a file. Currently, I want to use C# to extract out contents from the XML file and pass it as a string. For example in my XML file, I have a tag name. I want to use c# to extract the name from the XML file. How should I go about achieving it? Below is the sample code I have currently. The entire process must be carried out using a button click.

private void button1_Click(object sender, EventArgs e)
{
    XElement xml = XElement.Load("C:\\Windows 7.xml"); 
    IEnumerable<XElement> propertyIDs = xml.Descendants("PropertyId");

    foreach (XElement child in xml.Elements())
    {
        XElement row = child.Element("my:VM_Name");
        string test = xml.ToString();
        Console.WriteLine(test);
    }    
}

请访问此链接查看我的XML文件:< A HREF =http://pastebin.com/NKhBb4Zh相对=nofollow> http://pastebin.com/NKhBb4Zh

Please access this link to view my xml file: http://pastebin.com/NKhBb4Zh

推荐答案

我重写你的榜样,并把它改为使用XmlDocument类的。由于没有在命名空间,我不得不添加的 NameSpaceManager 的。 。使用这个,你甚至可以选择spefic节点

I rewrote your example and changed it to make use of the XmlDocument class. As there is the my Namespace I had to add a NameSpaceManager. using this you may even select a spefic node.

        string url = @"e:\temp\data.xml";

        XmlDocument doc = new System.Xml.XmlDocument();
        doc.Load(url);
        XmlElement docElement = doc.DocumentElement;

        /// loop through all childNodes
        foreach (XmlNode childNode in docElement.ChildNodes)
        {
            Console.WriteLine(childNode.Name + ": " + childNode.InnerText);
        }

        XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
        mgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-05-27T03:57:48");

        /// use the given XmlNamespaceManager to select a specific element
        XmlNode node = docElement.SelectSingleNode("my:VM_DiskSize", mgr);
        /// use innerText for node text and value for attributes only
        Console.WriteLine("\n" + node.Name + ": " + node.InnerText);



心连心

hth

这篇关于提取XML文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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