簡體   English   中英

如何使用C#獲取多個Childnode內部文本?

[英]How to Get more than one Childnode innertext using C#?

我正在讀取XML文件並將其存儲在表中,但是不幸的是我沒有獲得所有子節點的內部文本值,請找到我的xml文件和csharp編碼並提出解決方案。

XML:

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:ce="www.dummy.com" xmlns:mml="www.dummy.com">
<head>
<title></title>
</head>
<body>
<queries>
<query><label>1</label>Please check the first hierarchy.<page>1</page></query>
<query><label>2</label>Please check the second hierarchy.<page>12</page></query>
<query><label>3</label>Please check the third hierarchy.<page>13</page></query>
</queries>
</body>
</root>

Csharp編碼

XmlNodeList xnList2 = xml.SelectNodes("/root/body/queries");
            foreach (XmlNode xn2 in xnList2)
            {
                foreach (XmlNode childNode in xn2.ChildNodes)
                {

                    queries =xn2["query"].InnerText;
                    // text should return only first query text, but I need all the query text
                    query_string = "INSERT INTO Customer_Queries values ('"+ queries + "')";
                    SqlConnection myConnection = new SqlConnection(constr);
                    myConnection.Open();
                    SqlCommand myCommand = new SqlCommand(query_string, myConnection);
                    myCommand.ExecuteNonQuery();
                    myConnection.Close();

                }

我不知道我在哪里做錯了代碼。

第一個查詢文本針對所有三行重復插入

Please check the first hierarchy.

這應該工作:

    XmlNodeList xnList2 = xml.SelectNodes("/roor/body/queries");
                            foreach (XmlNode xn2 in xnList2)
                            {
                                foreach (XmlNode childNode in xn2.ChildNodes)
                                {

                                    queries = childNode.InnerText;
                                    // text should return only first query text, but I need all the query text
                                    query_string = "INSERT INTO Customer_Queries values (@query)";
                                    using(SqlConnection myConnection = new SqlConnection(constr))
                                    {
                                        myConnection.Open();
                                        using(SqlCommand myCommand = new SqlCommand(query_string, myConnection))
                                        {
                                           myCommand.parameters.AddWithValue("@query", queries);
                                           myCommand.ExecuteNonQuery();
                                        }
                                    }        
                                }
                            }

在foreach語句上,您聲明一個變量XmlNode childNode ,該變量將引用xn2每個節點。 所以,你需要使用childNode而不是xn2因為價值xn2永遠不會改變。 這就是為什么您總是獲得相同的價值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM