Search code examples
c#sql-serverxmlinfopath

foreach (xmlNode) only inserts the first value


I'm attempting to insert values from an MS Infopath repeating table into a SQL server DB using a web service, but only the first value gets inserted and duplicated depending on how many rows there are.

InfoPath

Form

Fields

SQL Server DB

Insert Result

Code

[WebMethod]
public void SubmitDocument(XmlDocument doc)
{
    string firstname;
    string lastname;

    XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
    nsManager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2018-08-16T17:55:49");
    nsManager.AddNamespace("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");

    XmlNode root = doc.DocumentElement;
    XmlNodeList list = root.SelectNodes("/dfs:IPDocument/my:myFields/my:UserList/my:Users", nsManager);

    foreach (XmlNode node in list)
    {
        firstname = node.SelectSingleNode("/dfs:IPDocument/my:myFields/my:UserList/my:Users/my:FirstName", nsManager).InnerText;
        lastname = node.SelectSingleNode("/dfs:IPDocument/my:myFields/my:UserList/my:Users/my:LastName", nsManager).InnerText;

        SubmitToDatabase(firstname, lastname);
    }
}

public void SubmitToDatabase(string firstname, string lastname)
{
    try
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO infopathconcepttable(FirstName, LastName)VALUES(@FirstName,@LastName)", conn);

            cmd.Parameters.AddWithValue("@FirstName", firstname);
            cmd.Parameters.AddWithValue("@LastName", lastname);

            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
    catch (SqlException ex)
    {

    }
}

Solution

  • I believe this has to do with providing an absolute XPath expression in your SelectSingleNode() call.

    Try relacing the two SelectSingleNode() calls with the following lines:

    firstname = node["FirstName", nsManager.LookupNamespace("my")].InnerText;
    lastname = node["LastName", nsManager.LookupNamespace("my")].InnerText;