开发者

Saving Particular Node in XML File

开发者 https://www.devze.com 2023-03-20 05:07 出处:网络
I am populating textboxes with information from a particular node based on it\'s ConfirmNum.Then when all info is updated, I am saving information (by a submit button) back to the particular node.

I am populating textboxes with information from a particular node based on it's ConfirmNum. Then when all info is updated, I am saving information (by a submit button) back to the particular node.

However, upon saving, every node in the XML file that was empty drops down to another line.

Example XML Before Save:

<OnlineBanking>
  <Transactions>
    <Txn>
      <Login></Login>
      <UserName>userName</UserName>
      <CustomerName>CustomerName</CustomerName>
      <ConfirmNum>1234</ConfirmNum>
    </Txn>
  </Transactions>
</OnlineBanking>

My code (below) will save the information for that node, based on the Page.aspx?CID=1234 number. However, every node in the entire XML file that was blank, will now have a line break in it. Not just the Txn we just edited, but all.

Here is my code:

protected void btnSubmit_Click(object sender, EventArgs e)
{
    XmlDocument item = new XmlDocument(开发者_如何学Go);
    item.Load(xmlFileName);
    if (CID != "")
    {
        XmlNode xlist = item.SelectSingleNode("OnlineBanking/Transactions/Txn[ConfirmNum=" + CID + "]");
        if (xlist != null)
        {
            xlist.ChildNodes.Item(0).InnerText = tbLogin.Text;
            xlist.ChildNodes.Item(1).InnerText = tbUserName.Text;
            xlist.ChildNodes.Item(2).InnerText = tbCustomerName.Text;
            item.Save(xmlFileName);
        }
    }
}

Example XML After Save:

<OnlineBanking>
  <Transactions>
    <Txn>
      <Login>
      </Login>
      <UserName>userName</UserName>
      <CustomerName>CustomerName</CustomerName>
      <ConfirmNum>1234</ConfirmNum>
    </Txn>
  </Transactions>
</OnlineBanking>

Note how the <login> is on another line than </login>. This is what I am talking about. Hope someone can see clearly what I am not doing.


Try setting the PreserveWhitespace property to True and see if it will stop inserting line breaks upon calling Save:

XmlDocument item = new XmlDocument();
item.PreserveWhitespace = true;
item.Load(xmlFileName);


One compromise is:

if(string.IsNullOrWhiteSpace(tbLogin.Text))
   xlist.ChildNodes.Item(0).IsEmpty = true;
else
   xlist.ChildNodes.Item(0).InnerText = tbLogin.Text;

This will give you:

<Login />
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号