简体   繁体   English

C#应用程序不会在XML文档中显示最后一个属性值

[英]C# application will not display last Attribute Value in XML Document

AC# project I am working on will not display/insert the last value within an XML tag. 我正在处理的AC#项目不会在XML标签中显示/插入最后一个值。 For Example my application iterates through this tag and will get 1, 2 3 but not 4. It does that with every iteration. 例如,我的应用程序遍历此标记,将得到1、2 3而不是4。它在每次迭代中都这样做。

<purpose>
 <intendedUse id="1"/>
 <intendedUse id="2"/>
 <intendedUse id="3"/>
 <intendedUse id="4"/>
</purpose>

I believe it has something to do with the int num declaration. 我相信这与int num声明有关。 NOTE: I commented my sqlite command so i wont write to the database. 注意:我注释了我的sqlite命令,所以我不会写到数据库。 I have a messagebox to display what the values will be. 我有一个消息框来显示值。

 for (i = 0; i < xmlnode.Count - 1; i++ )
            {
                str = xmlnode[i].Attributes[0].Value;
                int num = Int32.Parse(str) - 1;
                for ( var count = 0; count < xmlnode[num].FirstChild.NextSibling.ChildNodes.Count - 1; count++)
                {
                    str2 = xmlnode[num].FirstChild.NextSibling.ChildNodes[count].Attributes[0].Value; 
                    MessageBox.Show(str2);
                }

                //SQLiteCommand cmd = new SQLiteCommand(connection);
                //cmd.CommandText = "INSERT INTO languagePurpose (purposeID, languageID) VALUES ('" + str2 + "', '" + str + "')";
                //SQLiteDataReader dr = cmd.ExecuteReader();
               // MessageBox.Show(str);
            }

This probably isn't the answer you are looking for, but in Linq-to-XML this is very easy. 这可能不是您要找的答案,但是在Linq-to-XML中,这非常容易。 Lets assume you loaded your xml into a XDocument named "xml". 假设您将xml加载到名为“ xml”的XDocument

for(XNode node in xml.Element("purpose").Elements("intendedUse"))
{
    //sets the value of the id attribute to str2
    str2 = node.Attribute("id").Value;
}

With the above solution you can have a possible NullReferenceException if the no id attribute exists, or there's no "purpose" nodes, but the concept should be pretty clear from my example. 使用上述解决方案,如果不存在id属性或不存在“目的”节点,则可能会出现NullReferenceException ,但是从我的示例中应该可以很清楚地了解这一概念。

Obviously you can do whatever you want in there, but LINQ-to-XML is far easier to use than XmlDocument especially if you're trying to learn how to do XML parsing. 显然,您可以在其中执行任何操作,但是LINQ-to-XML比XmlDocument更易于使用,尤其是在您试图学习如何进行XML解析的情况下。

Here's a link to get you started: Linq-to-XML MSDN 这是让您入门的链接: Linq-to-XML MSDN

Figured it out. 弄清楚了。 I was supposed to remove the -1 in 我应该在中删除-1

count < xmlnode[num].FirstChild.NextSibling.ChildNodes.Count - 1`

Didnt notice until @Nadia brought it up for my first for loop, and I didn't notice that I added the -1 by habit. 直到@Nadia在我的第一个for循环中提出它时,我才注意到,并且我没有注意到我是按习惯加-1的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM