【问题标题】:Failing To Parse the XML File in C#无法在 C# 中解析 XML 文件
【发布时间】:2012-10-10 16:53:03
【问题描述】:

我是一名 C++ 开发人员,我开始从事 C# WPF 项目。我有一个应该读取 xml 文件的方法。在我的 c++ 应用程序中,我可以非常有效地做到这一点,但在 WPF 中,我不确定如何解决这个问题。让我给你看我的代码:

// When Browse Button is clicked this method is called
private void ExecuteScriptFileDialog()
    {
        var dialog = new OpenFileDialog { InitialDirectory = _defaultPath };
        dialog.DefaultExt = ".xml";
        dialog.Filter = "XML Files (*.xml)|*.xml";
        dialog.ShowDialog();
        ScriptPath = dialog.FileName; //ScriptPath contains the Path of the Xml File
        if (File.Exists(ScriptPath))
        {
            LoadAardvarkScript(ScriptPath);
        }
    }

    public void LoadAardvarkScript(string ScriptPath)
    {
        // I should read the xml file
    }

我在 C++ 中的实现如下:

File file = m_selectScript->getCurrentFile(); //m_selectScript is combobox name
if(file.exists())
{
   LoadAardvarkScript(file);
}

void LoadAardvarkScript(File file)
{   

XmlDocument xmlDoc(file);

//Get the main xml element
XmlElement *mainElement = xmlDoc.getDocumentElement();
XmlElement *childElement = NULL;
XmlElement *e = NULL;
int index = 0;
if(!mainElement )
{
    //Not a valid XML file.
    return ;
}

//Reading configurations...
if(mainElement->hasTagName("aardvark"))
{
    forEachXmlChildElement (*mainElement, childElement)
    {
        //Read Board Name
        if (childElement->hasTagName ("i2c_write"))
        {
            // Some code
        }
    }
}

如何像在我的 c++ 代码中那样获得 ma​​inElementchildelemtagname? :)

【问题讨论】:

  • 查看这个 StackOverFlow 发布它应该会给你一些想法stackoverflow.com/questions/8194155/c-sharp-parse-xml-file
  • 你能给我们看看 xml 以及你和它的内容吗!
  • 你为什么不直接使用XMLReader
  • @Ramhound:很遗憾我是这个 c# wpf 世界的新手。我还没做呢
  • 我刚刚将它发布到我的第一个答案的底部。如果您可以显示您的 XML 文件的格式,它也会有所帮助,因为如果您知道我的意思,有很多方法可以给猫剥皮

标签: c# .net xml


【解决方案1】:

这里不知道你的xml文件的布局是一个例子,如果你知道如何使用Linq就可以使用

class Program
{
    static void Main(string[] args)
    {
        XElement main = XElement.Load(@"users.xml");

        var results = main.Descendants("User")
            .Descendants("Name")
            .Where(e => e.Value == "John Doe")
            .Select(e => e.Parent)
            .Descendants("test")
            .Select(e => new { date = e.Descendants("Date").FirstOrDefault().Value, points = e.Descendants("points").FirstOrDefault().Value });

        foreach (var result in results)
            Console.WriteLine("{0}, {1}", result.date, result.points);
        Console.ReadLine();
    }
}

您也可以使用 XPATH 来解析 xml 文件.. 但确实需要查看 xml 文件布局

如果你想用 xmlreader 来做

使用 System.Collections.Generic; 使用 System.Linq; 使用 System.Text; 使用 System.Xml;

namespace XmlReading
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of the XmlTextReader and call Read method to read the file            
            XmlTextReader textReader = new XmlTextReader("C:\\myxml.xml");
            textReader.Read();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(textReader);

            XmlNodeList BCode = xmlDoc.GetElementsByTagName("Brandcode");
            XmlNodeList BName = xmlDoc.GetElementsByTagName("Brandname");
            for (int i = 0; i < BCode.Count; i++)
            {
                if (BCode[i].InnerText == "001")
                    Console.WriteLine(BName[i].InnerText);                
            }

            Console.ReadLine();
        }
    }
}

【讨论】:

  • 在这种情况下使用 XMLReader 不是更容易吗?为什么要使用 LINQ 使问题复杂化,除非它是一个非常复杂的 XML 文档。
  • @DJKRAZE:首先非常感谢您的帮助:) 那是问题伙伴。 XML 文件在我的办公室桌面上,我不知道它的结构。现在我无权访问它。我可以在明天同一时间为您提供文件。我希望你能在 Stackoverflow 上在线
【解决方案2】:

使用 LINQ 查询从 xml (XDocument) 中提取数据

请参阅此link,了解有关 Xlinq 的更多见解。

示例 XML:

 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<People>
<Person id="1">
<Name>Joe</Name>
<Age>35</Age>
<Job>Manager</Job>
</Person>

<Person id="2">
<Name>Jason</Name>
<Age>18</Age>
<Job>Software Engineer</Job>
</Person>

</People>

示例 Linq 查询:

var names = (from person in Xdocument.Load("People.xml").Descendants("Person")
        where int.Parse(person.Element("Age").Value) < 30
        select person.Element("Name").Value).ToList();

名称将是字符串列表。此查询将返回 Jason,因为他 18 岁。

【讨论】:

  • OP 是 C++ 开发人员 Rakesh,所以也许你可以展示一个代码示例来帮助他。希望他理解 Linq
  • @StonedJesus:别担心,伙计……上面的例子对你有帮助吗?您还可以使用 LINQPad 直观地创建查询。 linqpad.net
  • @RakeshGunijan:谢谢哥们 :) 但我根本没有研究过 LINQ。
  • 你能分享一个伪xml结构(填充虚拟数据)。然后我可以为您提供查询。
  • @RakeshGunijan:那就是问题伙伴。 XML 文件在我的办公室桌面上,我不知道它的结构。现在我无权访问它。我可以在明天同一时间为您提供文件。我希望你能在 Stackoverflow 上在线 :)
【解决方案3】:

使用Linq2Xml

var xDoc = XDocument.Load("myfile.xml");

var result = xDoc.Descendants("i2c_write")
                .Select(x => new
                {
                    Addr = x.Attribute("addr").Value,
                    Count = x.Attribute("count").Value,
                    Radix = x.Attribute("radix").Value,
                    Value = x.Value,
                    Sleep = ((XElement)x.NextNode).Attribute("ms").Value 
                })
                .ToList();

var khz = xDoc.Root.Element("i2c_bitrate").Attribute("khz").Value;

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2019-08-06
    • 1970-01-01
    • 2012-01-01
    • 2023-04-07
    相关资源
    最近更新 更多