从XML文件读取元素 [英] Reading elements from XML file

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

问题描述

我正在尝试读取XML文件并将元素输入到单独的字符串中.我设法将元素写入数组,然后放入字符串中,但这似乎是一种非常糟糕的方法.我对此很陌生,只是把我在互联网上发现的东西拼凑在一起,所以似乎写的都不好(这就是我在这里的原因):)

因此,我的XML文件的简化版本看起来像这样:

I''m trying to read an XML file and input the elements into separate strings. I have managed to write the elements to an array and then afterwards put then into strings but this seems like a really bad way of doing it. I''m very new to this and am just piecing together bits I find off the internet so it may all seem really badly written (which is why I''m on here):)

So a shortened version of my XML file looks a bit like this:

<?xml version="1.0" encoding="utf-8" ?>
<CompanyDetails>
  <CompanyName>Companyname</CompanyName>
  <Address1>address1</Address1>
  <Address2>address2</Address2>  <!-- If no Address2 then enter NA -->>
  </CompanyDetails>



还有更多元素,但只有一个"CompanyDetails",我想我可以说获取CompanyName并分配给字符串strCompanyName",然后获取下一个元素,等等.这是我目前的代码:



There are more elements but just one ''CompanyDetails'' I thought I would be able to say "Get CompanyName and assign to string strCompanyName" then get the next element etc. This is the code I have at the moment:

XmlTextReader READER = new XmlTextReader(strPath);

            while (READER.Read())
            {
                XmlNodeType NODETYPE = READER.NodeType;
                switch (NODETYPE)
                {
                    case XmlNodeType.Element:
                        if (READER.HasAttributes)
                        {
                            for (int i = 0; i < READER.AttributeCount; i++)
                            {
                                READER.MoveToAttribute(i);
                            }
                        }
                        break;
                    case XmlNodeType.Text:
                        arrStore[intCounter] = READER.Value;
                        intCounter++;

                        break;

                }
            }

            strCompanyName = arrStore[0];
            strAddress1 = arrStore[1];
            strAddress2 = arrStore[2];
            if (strAddress2 == "NA") strAddress2 = "";
            strCity = arrStore[3];
            strCounty = arrStore[4];
            strPostcode = arrStore[5];
            strTel = arrStore[6];
            strFax = arrStore[7];
            strLogo = arrStore[8];
            strSigName = arrStore[9];



因此,我遍历整个过程并将所有元素放入一个Array中,然后最后一个块将它们分配给字符串.麻烦的是,代码无法识别正在读取的数据,因此如果说address2没有值,则会弄乱我的代码.有人可以帮忙吗?我确信XML应该使读取这样的数据更加容易.如前所述,XML中只有一个CompanyName.我只删除了大约5行,例如城市,县,邮政编码等




So I pass through the whole thing and put all of the elements into an Array, then the final block assigns them to strings. Trouble is, the code does not recognise the data it is reading so if say address2 does not have a value, it messes up my code. Could anybody help? I''m sure XML should make it easier to read data like this. As I said before, there is only one CompanyName in the XML. I have only removed about 5 lines like city, county, postcode etc


I tried this code but I am getting a compile error:


Error 2
The best overloaded method match for 'System.Xml.XmlNode.this[string]' has some invalid arguments

This is my code so far:
void GetXMLValues(string strFilePath)
        {
            MessageBox.Show(strFilePath);
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(strFilePath);
            XmlNode node = xmlDoc.SelectSingleNode("/CompanyDetails");

            strCompanyName = node[0]; // this is the offending line, it underlines the node[0] part
}

Any suggestions?

推荐答案

请在CP上阅读此文章: ^ ]告诉您如何使用XPath表达式剖析XML documnet.在这里找到另一个很好的资源: http://www.w3.org/TR/xpath/ [ ^ ].

祝您编程愉快!

-MRB
Please read this article here on CP: Using XPathNavigator in C#[^] it tells you how to dissect an XML documnet using XPath expressions. Another good resource is found here: http://www.w3.org/TR/xpath/[^].

Happy coding!

-MRB


您可以使用XPath而不是像上面那样查询它.您可以避免编写这些案例并使之简短明了.
如果您有巨大的XML文件,通常应使用XmlTextReader.

You can use XPath instead of querying it like you did above. You can avoid writing those cases and make it short and simple.
XmlTextReader should be generally used if you have a huge XML file.

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

//to get all the elements in the element 'CompanyName', do this :

XmlNode node= xmlDoc.SelectSingleNode("/CompanyDetails");   //specify the Xpath as "/CompanyDetails"
strCompanyName = node[0].InnerText;  // will return CompanyName node
strAddress1 = node[1].InnerText;     // will return Address1 node
//etc and then go on



如果需要特定元素,可以说CompanyName,
那么您的XPath将如下所示:
"/CompanyDetails/CompanyName"

更新:在节点[0]和节点[1]之后添加了"InnerText".



If you want a specific element, lets say CompanyName,
then your XPath will be like this :
"/CompanyDetails/CompanyName"

Update : Added "InnerText" after node[0] and node[1].


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

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