Member 11399563 Ответов: 1

Как добавить/добавить мой XML out put в существующий XML-файл


I am stuck with some code please help

written the code to reads the few content from the word and writes the data to xml file.

new requirement is 

i need to append these details to existing xml file instead of ovverwritting


HTML:




code behind file:

using Microsoft.Office.Interop.Word;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Table = Microsoft.Office.Interop.Word.Table;


namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            Application app = new Application();
            Document doc = new Document();


            try
            {
                List<string> data = new List<string>();
                WordFileToRead.SaveAs(Server.MapPath(WordFileToRead.FileName));
                object filename = Server.MapPath(WordFileToRead.FileName);

                doc = app.Documents.Open(ref filename);
                foreach (Table tb in doc.Tables)
                {
                    for (int row = 1; row <= tb.Rows.Count; row++)
                    {
                        var cell = tb.Cell(row, 1);
                        var text = cell.Range.Text;

                        var value = tb.Cell(row, 2);
                        var result = value.Range.Text;

                        if (text == "Originator:\r\a")
                        {
                            txtOriginator.Text = result;
                        }
                        else if (text == "Content:\r\a")
                        {
                            txtContent.Text = result;
                        }
                        else if (text == "Begin Date of Message:\r\a")
                        {
                            txtStartDate.Text = result;
                        }
                        else if (text == "End Date of Message:\r\a")
                        {
                            txtEnddate.Text = result;
                        }
                        else if (text == "Parameter (Choose from list, below):\r\a")
                        {
                            txtParameter.Text = result;
                        }
                        else if (text == "*Value/Threshold for Parameter: \r\a")
                        {
                            txtStateCode.Text = result;
                        }
                        else if (text == "Invoice Template (Choose from list below):\r\a")
                        {
                            txtinvoicetemplatelist.Text = result;
                        }

                    }
                }

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                ((_Document)doc).Close();
                ((_Application)app).Quit();
            }



        }

        public void btnSubmit_Click(object sender, EventArgs e)
        {


            string stDate = RemoveInvalidXmlChars(txtStartDate.Text);
            //string formatted = stDate.ToString("ddMMyyyy");
            string endDate = RemoveInvalidXmlChars(txtEnddate.Text);
            string content = RemoveInvalidXmlChars(txtContent.Text);
            string originator = RemoveInvalidXmlChars(txtOriginator.Text);
            string stateCode = RemoveInvalidXmlChars(txtStateCode.Text);
            string param = RemoveInvalidXmlChars(txtParameter.Text);
            string invoiceTemplateList = RemoveInvalidXmlChars(txtinvoicetemplatelist.Text);




            XmlDocument Doc = new XmlDocument();
            XmlDeclaration dec = Doc.CreateXmlDeclaration("1.0", null, null);
            Doc.AppendChild(dec);



            XmlElement DocRoot = Doc.CreateElement("Message");
            Doc.AppendChild(DocRoot);
            XmlAttribute Attr_ID = Doc.CreateAttribute("Id");          
            Attr_ID = Doc.CreateAttribute("Id");

            DateTime time1 = Convert.ToDateTime(stDate);           
            Attr_ID.Value = time1.ToString("yyyymmdd");      
            DocRoot.Attributes.Append(Attr_ID);


            Attr_ID = Doc.CreateAttribute("StartDate");
            DateTime time3 = Convert.ToDateTime(stDate);
            Attr_ID.Value = time3.ToString("yyyymmdd");            
            DocRoot.Attributes.Append(Attr_ID);

            Attr_ID = Doc.CreateAttribute("EndDate");

            DateTime time2 = Convert.ToDateTime(endDate);              
            Attr_ID.Value = time2.ToString("yyyymmdd");
            DocRoot.Attributes.Append(Attr_ID);
            Doc.AppendChild(DocRoot);

            XmlNode conditions = Doc.CreateElement("Conditions");
            DocRoot.AppendChild(conditions);



            XmlNode condition = Doc.CreateElement("Condition");
            XmlAttribute attrcondition = Doc.CreateAttribute("Boolean");
            attrcondition.Value = "AND";
            condition.Attributes.Append(attrcondition);
            conditions.AppendChild(condition);


            XmlNode Parameter = Doc.CreateElement("Parameter");
            XmlAttribute attParam = Doc.CreateAttribute("FieldName");
            attParam = Doc.CreateAttribute("FieldName");
            attParam.Value = "InvoiceDate";
            Parameter.Attributes.Append(attParam);
            attParam = Doc.CreateAttribute("Operator");
            attParam.Value = "GTE";
            Parameter.Attributes.Append(attParam);
            attParam = Doc.CreateAttribute("Value");
            attParam.Value = time3.ToString("yyyymmdd"); 
            Parameter.Attributes.Append(attParam);
            condition.AppendChild(Parameter);

            XmlNode Parameter2 = Doc.CreateElement("Parameter");
            XmlAttribute attParam2 = Doc.CreateAttribute("FieldName");
            attParam2 = Doc.CreateAttribute("FieldName");
            attParam2.Value = "InvoiceDate";
            Parameter2.Attributes.Append(attParam2);
            attParam2 = Doc.CreateAttribute("Operator");
            attParam2.Value = "LTE";
            Parameter2.Attributes.Append(attParam2);
            attParam2 = Doc.CreateAttribute("Value");
            attParam2.Value = time2.ToString("yyyymmdd");
            DateTime time4 = Convert.ToDateTime(endDate);
            Attr_ID.Value = time4.ToString("yyyymmdd");
            Parameter2.Attributes.Append(attParam2);
            condition.AppendChild(Parameter2);


            XmlNode Parameter3 = Doc.CreateElement("Parameter");
            XmlAttribute attParam3 = Doc.CreateAttribute("StateCode");
            attParam3 =Doc.CreateAttribute("FieldName");
            attParam3.Value = "StateCode";
            Parameter3.Attributes.Append(attParam3);
            attParam3 = Doc.CreateAttribute("Operator");
            attParam3.Value = "EQ";
            Parameter3.Attributes.Append(attParam3);
            attParam3 = Doc.CreateAttribute("Value");
            attParam3.Value = "NY";
            Parameter3.Attributes.Append(attParam3);
            condition.AppendChild(Parameter3);

            XmlNode server = Doc.CreateElement("Content");
            DocRoot.AppendChild(server);
            XmlAttribute contentAttr = Doc.CreateAttribute("Class");
            contentAttr.Value = "MarketingMessage";
            server.Attributes.Append(contentAttr);
            XmlNode line = Doc.CreateElement("line");
            server.AppendChild(line);
            line.InnerText = content;


            Doc.Save("C:\\Users\\ab85556\\Desktop\\Message.xml");
            // Doc.Save("C:\\Users\\ab85556\\Desktop\\Message.xml");

            Doc.DocumentElement.AppendChild(DocRoot);

            //adding aattribute to existing xml file

            // C:\\Users\\ab85556\\Desktop\\SaveData.xml


        }

        public static string RemoveInvalidXmlChars(string input)
        {
            return new string(input.Where(value =>
                (value >= 0x0020 && value <= 0xD7FF) ||
                (value >= 0xE000 && value <= 0xFFFD) ||
                value == 0x0009 ||
                value == 0x000A ||
                value == 0x000D).ToArray());
        }
    }

}


output of this code is :
---------------------------------

<message id="20180001" startdate="20180001" enddate="20180031">
  <content class="MarketingMessage">
    <line>Effective March 1, 2018, the California Advanced Services Fund (CASF) surcharge will increase from 0.0% to 0.56%. If you have any questions, please call a Customer Care Representative at the telephone number located in the My Account or Important News sections of your bill.

  
  <conditions>
    <condition boolean="AND">
      <parameter fieldname="InvoiceDate" operator="GTE" value="20180001">
      <parameter fieldname="InvoiceDate" operator="LTE" value="20180031">
      <parameter fieldname="StateCode" operator="EQ" value="NY">
    
  


I want to append this content to existing file which has data like 
------------------------------------------------------------------

<messages>
  <message id="01984" zone="P1_MA_SS_Marketing" priority="10" startdate="20050627" enddate="20050811">
    <conditions>
      <condition boolean="AND">
        <parameter fieldname="OtherProviderServiceFlag" operator="EQ" value="N">
        <parameter fieldname="Buyer" operator="EQ" value="Q">
        <parameter fieldname="StateCode" operator="EQ" value="OK">
      
    
    <content class="MarketingMessage">
      <line>Current Charges will be considered Past
      <line>
        <text>Due on 
        <data>
      </data>
    
  
  <message id="01988" zone="P1_MA_SS_Marketing" priority="20" startdate="" enddate="">    <conditions>
      <condition boolean="AND">
        <parameter fieldname="OtherProviderServiceFlag" operator="EQ" value="N">
        <parameter fieldname="Buyer" operator="EQ" value="Q">
        <parameter fieldname="Partner" operator="NEQ" value="AMEX">
        <parameter fieldname="PaymentMethodUsed" operator="NEQ" value="CC">
        <parameter fieldname="PaymentMethodUsed" operator="NEQ" value="PS">
      
    
    <content class="MarketingMessage">
      <line>You make the call. CenturyLink allows you to make the bill payment choice that best suits your individual needs. You have the choice of paying your CenturyLink bill by check, money order, Visa, MasterCard, or Discover. Why not explore the convenience and savings of using your credit card to automatically pay your bill each month? To pay your invoice with your credit card or to sign up for recurring billing, please visit https://residential.centurylink.com/account/menu.jsp or call 1-800-860-2255.
    
  
  <message id="01990" zone="P1_MA_SS_Marketing" priority="25" startdate="" enddate="">

    <conditions>
      <condition boolean="AND">
        <parameter fieldname="OtherProviderServiceFlag" operator="EQ" value="N">
        <parameter fieldname="Buyer" operator="EQ" value="Q">
        <parameter fieldname="ProductCode" operator="NEQ" value="INTLQ5">
      
    
    <content class="MarketingMessage">
      <line>Save BIG on all your international calls with CenturyLink's international calling plans. Receive CenturyLink's lowest international rates 24 hours-a-day, 7 days-a-week! Call today to see how much you can save to the countries you call the most.
    


  //above message code should come here 




please help

What I have tried:

i have tried to load few data from word file to asp.net controls- saving these contents to XML file 

now i want to add this content to end of the existing file(xml file)

please help me

1 Ответов

Рейтинг:
10

#realJSOP

Используйте LinqwToXML для загрузки документа, добавления новых данных и сохранения документа. Легкий гороховый лимонный сок.


Member 11399563

Привет #realJSOP,

Есть ли у вас какой-нибудь пример кода, Как выполнить такую задачу? если да, то, пожалуйста, предоставьте.

#realJSOP

Гугл знает. Вы также можете выполнить поиск в CodeProject.