Создание разных XML-файлов для каждой строки базы данных

#c# #.net #xml #database #datatable

#c# #.net #xml #База данных #datatable

Вопрос:

у меня есть проект, в котором я должен генерировать разные XML-файлы для каждой строки базы данных. Я создал классы для xml, но мне не ясно, как я могу их заполнить. вот классы:

      Xml2CSharp.GTalkMessage gTalkMessage = new Xml2CSharp.GTalkMessage
        {
            EnvelopeVersion = "2.0",
            Header = "",
            GovTalkDetails = "",
            Body = "",
            Xmlns = "",
        };
        Xml2CSharp.Body body = new Xml2CSharp.Body
        {
            MessageRequest = "",
        };
        Xml2CSharp.MessageRequest messageRequest = new Xml2CSharp.MessageRequest
        {
            OecdMessage = "",
            FinancialInstitutionName = "",
            NUIS = "",
            SendDateTime = "",
            Xmlns = "",
        };
        Xml2CSharp.OecdMessage oecdMessage = new Xml2CSharp.OecdMessage
        {
            MessageSpec = "",
            CrsBody = "",
            Crs = "",
            Cfc = "",
            Stf = "",
            Ftc = "",
        };
        Xml2CSharp.CrsBody crsBody = new Xml2CSharp.CrsBody
        {
            ReportingFI = "",
            ReportingGroup = "",
        };
        Xml2CSharp.ReportingGroup reportingGroup = new Xml2CSharp.ReportingGroup
        {
            AccountReport = "",
        };
        Xml2CSharp.AccountReport accountReport = new Xml2CSharp.AccountReport
        {
            DocSpec = "",
            AccountNumber = "",
            AccountHolder = "",
            AccountBalance = "",
        };
        Xml2CSharp.AccountBalance accountBalance = new Xml2CSharp.AccountBalance
        {
            CurrCode = "",
            Text = "",
        };
        Xml2CSharp.AccountHolder accountHolder = new Xml2CSharp.AccountHolder
        {
            Individual = "",
        };
        Xml2CSharp.Individual individual = new Xml2CSharp.Individual
        {
            ResCountryCode = "",
            TIN = "",
            Name = "",
            Address = "",
            BirthInfo = "",
        };
        Xml2CSharp.BirthInfo birthInfo = new Xml2CSharp.BirthInfo
        {
            BirthDate = "",
            CountryInfo = "",
        };
        Xml2CSharp.CountryInfo countryInfo = new Xml2CSharp.CountryInfo
        {
            CountryCode = "",

        };
        Xml2CSharp.Name name = new Xml2CSharp.Name
        {
            FirstName = "",
            LastName = "",
        };
        Xml2CSharp.TIN TIN = new Xml2CSharp.TIN
        {
            IssuedBy = "",
            Text = "",
        };
        Xml2CSharp.AccountNumber AccountNumber = new Xml2CSharp.AccountNumber
        {
            AcctNumberType = "",
            UndocumentedAccount = "",
            ClosedAccount = "",
            DormantAccount = "",
        };
        Xml2CSharp.ReportingFI ReportingFI = new Xml2CSharp.ReportingFI
        {
            ResCountryCode = "",
            IN = "",
            Name = "",
            Address = "",
            DocSpec = "",
        };
        Xml2CSharp.DocSpec DocSpec = new Xml2CSharp.DocSpec
        {
            DocTypeIndic = "",
            DocRefId = "",
        };
        Xml2CSharp.Address Address = new Xml2CSharp.Address
        {
            CountryCode = "",
            AddressFix = "",
        };
        Xml2CSharp.AddressFix AddressFix = new Xml2CSharp.AddressFix
        {
            Street = "",
            PostCode = "",
            City = "",
        };
        Xml2CSharp.IN IN = new Xml2CSharp.IN
        {
            IssuedBy = "",
            Text = "",
        };
        Xml2CSharp.MessageSpec MessageSpec = new Xml2CSharp.MessageSpec
        {
            SendingCompanyIN = "",
            TransmittingCountry = "",
            ReceivingCountry = "",
            MessageType = "",
            MessageRefId = "",
            MessageTypeIndic = "",
            ReportingPeriod = "",
            Timestamp = "",
        };
        Xml2CSharp.GTalkDetails GTalkDetails = new Xml2CSharp.GTalkDetails
        {
            Keys = "",
        };
        Xml2CSharp.Keys Keys = new Xml2CSharp.Keys
        {
            Key = "",
        };
        Xml2CSharp.Key Key = new Xml2CSharp.Key
        {
            Type = "",
            Text = "",
        };
        Xml2CSharp.Header Header = new Xml2CSharp.Header
        {
            MessageDetails = "",
            SenderDetails = "",
        };
        Xml2CSharp.SenderDetails SenderDetails = new Xml2CSharp.SenderDetails
        {
            IDAuthentication = "",
        };
        Xml2CSharp.IDAuthentication IDAuthentication = new Xml2CSharp.IDAuthentication
        {
            SenderID = "",
            Authentication = "",
        };
        Xml2CSharp.Authentication Authentication = new Xml2CSharp.Authentication
        {
            Method = "",
            Value = "",
        };
        Xml2CSharp.MessageDetails MessageDetails = new Xml2CSharp.MessageDetails
        {
            Class = "",
            Qualifier = "",
            Function = ""
        };

        XmlSerializer serializer = new XmlSerializer(typeof(GTalkMessage));
        serializer.Serialize(File.Create("fileTest.xml"), gTalkMessage);
  

вот XML, который мне нужно сгенерировать:

 <GTalkMessage xmlns="http:/xxxxxxxxxxxx">
  <EnvelopeVersion>2.0</EnvelopeVersion>
  <Header>
    <MessageDetails>
      <Class>Dxxxxxxx</Class>
      <Qualifier>request</Qualifier>
      <Function>submit</Function>
    </MessageDetails>
    <SenderDetails>
      <IDAuthentication>
        <SenderID>tttttt1</SenderID>
        <Authentication>
          <Method>clear</Method>
          <Value>b@xxxxxxxxxxxx</Value>
        </Authentication>
      </IDAuthentication>
    </SenderDetails>
  </Header>
  <GovTalkDetails>
    <Keys>
      <Key Type="SpokeName">mmmmmmm</Key>
    </Keys>
  </GovTalkDetails>
  <Body>
    <MessageRequest xmlns="http://xxxxxxxx">
      <OecdMessage xmlns:crs="urn: oecd:ties: crs:v1"
                   xmlns:cfc="urn:oecd:ties:commontypesfatcacrs:v1"
                   xmlns:stf="urn: oecd:ties: stf:v4"
                   xmlns:ftc="urn: oecd:ties: fatca:v1">
        <crs:MessageSpec>
          <crs:SendingCompanyIN>99999999</crs:SendingCompanyIN>
          <crs:TransmittingCountry>ak</crs:TransmittingCountry>
          <crs:ReceivingCountry>ak</crs:ReceivingCountry>
          <crs:MessageType>CRS</crs:MessageType>
          <crs:MessageRefId>0987654321</crs:MessageRefId>
          <crs:MessageTypeIndic>CRS701</crs:MessageTypeIndic>
          <crs:ReportingPeriod>2019-12-31</crs:ReportingPeriod>
          <crs:Timestamp>2020-09-18T09:33:00</crs:Timestamp>
        </crs:MessageSpec>
        <crs:CrsBody>
          <crs:ReportingFI>
            <crs:ResCountryCode>AL</crs:ResCountryCode>
            <crs:IN issuedBy="ak">999999</crs:IN>
            <crs:Name>Eeeeee</crs:Name>
            <crs:Address>
              <cfc:CountryCode>ak</cfc:CountryCode>
              <cfc:AddressFix>
                <cfc:Street>Rruga</cfc:Street>
                <cfc:PostCode>uuuu</cfc:PostCode>
                <cfc:City>aaaa«</cfc:City>
              </cfc:AddressFix>
            </crs:Address>
            <crs:DocSpec>
              <stf:DocTypeIndic>aaaa</stf:DocTypeIndic>
              <stf:DocRefId>0123456789</stf:DocRefId>
            </crs:DocSpec>
          </crs:ReportingFI>
          <crs:ReportingGroup>
            <crs:AccountReport>
              <crs:DocSpec>
                <stf:DocTypeIndic>OECD1</stf:DocTypeIndic>
                <stf:DocRefId>0123456789</stf:DocRefId>
              </crs:DocSpec>
              <crs:AccountNumber AcctNumberType="pppppp"
                    UndocumentedAccount="false" ClosedAccount="false"
                  DormantAccount="false">0123456789</crs:AccountNumber>
              <crs:AccountHolder>
                <crs:Individual>
                  <crs:ResCountryCode>Ak</crs:ResCountryCode>
                  <crs:TIN issuedBy="Ak">bbbbbbb</crs:TIN>
                  <crs:Name>
                    <crs:FirstName>yyy</crs:FirstName>
                    <crs:LastName>yyy</crs:LastName>
                  </crs:Name>
                  <crs:Address>
                    <cfc:CountryCode>Ak</cfc:CountryCode>
                    <cfc:AddressFix>
                      <cfc:PostCode>uuu1</cfc:PostCode>
                      <cfc:City>oooooo</cfc:City>
                    </cfc:AddressFix>
                  </crs:Address>
                  <crs:BirthInfo>
                    <crs:BirthDate>1988-02-02</crs:BirthDate>
                    <crs:CountryInfo>
                      <crs:CountryCode>AL</crs:CountryCode>
                    </crs:CountryInfo>
                  </crs:BirthInfo>
                </crs:Individual>
              </crs:AccountHolder>
              <crs:AccountBalance currCode="EUR">25000.00</crs:AccountBalance>
            </crs:AccountReport>
          </crs:ReportingGroup>
        </crs:CrsBody>
      </OecdMessage>
      <FinancialInstitutionName>test</FinancialInstitutionName>
      <NUIS>9999999</NUIS>
      <SendDateTime>2020-08-31</SendDateTime>
    </MessageRequest>
  </Body>
</GTalkMessage>
  

и вот как я думал получить данные из базы данных:

    DataTable dt = new DataTable();
        DataSet ds = new DataSet();

        dt = GetRecordDetails();    

        ds.Tables.Add(dt);
        ds.Tables[0].TableName = "";
  

можете ли вы помочь мне назначить данные тегам, которым они принадлежат?

Комментарии:

1. Можете ли вы опубликовать образец xml для одной строки?

Ответ №1:

Вот что я бы сделал

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication1
{

    class Program
    {
        const string FILENAME = @"c:temptest.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XElement xGTalkMessage = doc.Root;
            XNamespace ns = xGTalkMessage.GetDefaultNamespace();
            XElement xHeader = xGTalkMessage.Descendants(ns   "Header").FirstOrDefault();
            XElement xBody = xGTalkMessage.Descendants(ns   "Body").FirstOrDefault();


            XElement EnvelopeVersion = xGTalkMessage.Descendants(ns   "EnvelopeVersion").FirstOrDefault();
            EnvelopeVersion.SetValue("new value");
            XElement Class = xHeader.Descendants(ns   "Class").FirstOrDefault();
            Class.SetValue("new value");
            XElement Qualifier= xHeader.Descendants(ns   "Qualifier").FirstOrDefault();
            Qualifier.SetValue("new value");
            XElement Function = xHeader.Descendants(ns   "Function").FirstOrDefault();
            Function.SetValue("new value");
            XElement SenderID = xHeader.Descendants(ns   "SenderID").FirstOrDefault();
            SenderID.SetValue("new value");
            XElement Method = xHeader.Descendants(ns   "Method").FirstOrDefault();
            Method.SetValue("new value");
            XElement Value =  xHeader.Descendants(ns   "Value").FirstOrDefault();
            Value.SetValue("new value");
           
            XElement xMessageRequest = xBody.Descendants().Where(x => x.Name.LocalName == "MessageRequest").FirstOrDefault();
            ns = xMessageRequest.GetDefaultNamespace();
            XElement xOecdMessage = xMessageRequest.Element(ns   "OecdMessage");
            XNamespace nsCrs = xOecdMessage.GetNamespaceOfPrefix("crs");
            XNamespace nsCfc = xOecdMessage.GetNamespaceOfPrefix("cfc");
            XNamespace nsStf = xOecdMessage.GetNamespaceOfPrefix("stf");
            XElement xMessageSpec = xOecdMessage.Element(nsCrs   "MessageSpec");

            XElement SendingCompanyIN = xMessageSpec.Element(nsCrs   "SendingCompanyIN");
            SendingCompanyIN.SetValue("new value");
            XElement TransmittingCountry = xMessageSpec.Element(nsCrs   "TransmittingCountry");
            TransmittingCountry.SetValue("new value");
            XElement ReceivingCountry = xMessageSpec.Element(nsCrs   "ReceivingCountry");
            ReceivingCountry.SetValue("new value");
            XElement MessageType = xMessageSpec.Element(nsCrs   "MessageType");
            MessageType.SetValue("new value");
            XElement MessageRefId = xMessageSpec.Element(nsCrs   "MessageRefId");
            MessageRefId.SetValue("new value");
            XElement MessageTypeIndic = xMessageSpec.Element(nsCrs   "MessageTypeIndic");
            MessageTypeIndic.SetValue("new value");
            XElement ReportingPeriod = xMessageSpec.Element(nsCrs   "ReportingPeriod");
            ReportingPeriod.SetValue("new value");
            XElement Timestamp = xMessageSpec.Element(nsCrs   "Timestamp");
            Timestamp.SetValue("new value");
            XElement FinancialInstitutionName = xMessageRequest.Element(ns   "FinancialInstitutionName");
            FinancialInstitutionName.SetValue("new value");
            XElement NUIS = xMessageRequest.Element(ns   "NUIS");
            NUIS.SetValue("new value");
            XElement SendDateTime = xMessageRequest.Element(ns   "SendDateTime");
            SendDateTime.SetValue("new value");

            XElement xReportingFI = xOecdMessage.Descendants(nsCrs   "ReportingFI").FirstOrDefault();

            XElement ResCountryCode = xReportingFI.Element(nsCrs   "ResCountryCode");
            ResCountryCode.SetValue("new value");
            XElement IN = xReportingFI.Element(nsCrs   "IN");
            IN.SetValue("new value");
            XAttribute issuedBy = xReportingFI.Element(nsCrs   "IN").Attribute("issuedBy");
            issuedBy.SetValue("new value");
            XElement Name = xReportingFI.Element(nsCrs   "Name");
            Name.SetValue("new value");
            XElement CountryCode = xReportingFI.Descendants(nsCfc   "CountryCode").FirstOrDefault();
            CountryCode.SetValue("new value");
            XElement Street = xReportingFI.Descendants(nsCfc   "Street").FirstOrDefault();
            Street.SetValue("new value");
            XElement PostCode = xReportingFI.Descendants(nsCfc   "PostCode").FirstOrDefault();
            PostCode.SetValue("new value");
            XElement City = xReportingFI.Descendants(nsCfc   "City").FirstOrDefault();
            City.SetValue("new value");
            XElement DocTypeIndic = xReportingFI.Descendants(nsStf   "DocTypeIndic").FirstOrDefault();
            DocTypeIndic.SetValue("new value");
            XElement DocRefId = xReportingFI.Descendants(nsStf   "DocRefId").FirstOrDefault();
            DocRefId.SetValue("new value");

            XElement xAccountReport = xGTalkMessage.Descendants(nsCrs   "AccountReport").FirstOrDefault();

            XElement AccountDocTypeIndic = xAccountReport.Descendants(nsStf   "DocTypeIndic").FirstOrDefault();
            AccountDocTypeIndic.SetValue("new value");
            XElement AccountDocRefId = xAccountReport.Descendants(nsStf   "DocRefId").FirstOrDefault();
            AccountDocRefId.SetValue("new value");

            XElement xAccountNumber = xAccountReport.Element(nsCrs   "AccountNumber");
            xAccountNumber.SetValue("new value");
            XAttribute AcctNumberType = xAccountNumber.Attribute("AcctNumberType");
            AcctNumberType.SetValue("new value");
            XAttribute UndocumentedAccount = xAccountNumber.Attribute("UndocumentedAccount");
            UndocumentedAccount.SetValue("new value");
            XAttribute ClosedAccount = xAccountNumber.Attribute("ClosedAccount");
            ClosedAccount.SetValue("new value");
            XAttribute DormantAccount = xAccountNumber.Attribute("DormantAccount");
            DormantAccount.SetValue("new value");

            XElement IndResCountryCode = xAccountReport.Descendants(nsCrs   "ResCountryCode").FirstOrDefault();
            IndResCountryCode.SetValue("new value");
            XElement TIN = xAccountReport.Descendants(nsCrs   "TIN").FirstOrDefault();
            TIN.SetValue("new value");
            XAttribute TINissuedBy = xAccountReport.Descendants(nsCrs   "TIN").FirstOrDefault().Attribute("issuedBy");
            TINissuedBy.SetValue("new value");
            XElement FirstName = xAccountReport.Descendants(nsCrs   "FirstName").FirstOrDefault();
            FirstName.SetValue("new value");
            XElement LastName = xAccountReport.Descendants(nsCrs   "LastName").FirstOrDefault();
            LastName.SetValue("new value");
            XElement AddrressCountryCode = xAccountReport.Descendants(nsCfc   "CountryCode").FirstOrDefault();
            AddrressCountryCode.SetValue("new value");
            XElement AddressPostCode = xAccountReport.Descendants(nsCfc   "PostCode").FirstOrDefault();
            AddressPostCode.SetValue("new value");
            XElement AddressCity = xAccountReport.Descendants(nsCfc   "City").FirstOrDefault();
            AddressCity.SetValue("new value");
            XElement BirthDate = xAccountReport.Descendants(nsCrs   "BirthDate").FirstOrDefault();
            BirthDate.SetValue("new value");
            XElement BirthCountryCode = xAccountReport.Descendants(nsCrs   "CountryCode").FirstOrDefault();
            BirthCountryCode.SetValue("new value");
            XElement AccountBalance = xAccountReport.Descendants(nsCrs   "AccountBalance").FirstOrDefault();
            AccountBalance.SetValue("new value");
            XAttribute AccountBalanceCurrCode = xAccountReport.Descendants(nsCrs   "AccountBalance").FirstOrDefault().Attribute("currCode");
            AccountBalanceCurrCode.SetValue("new value");

            string xml = doc.ToString();
        }
    }
}
  

Комментарии:

1. Вы имеете в виду, что я должен удалить созданные классы? и c:temptest.xml является ли пустой XML-файл?

2. Если вы создаете datatable прямо из xml, вам не нужны классы. Я просто поместил ваш xml в файл для тестирования. Вы можете проанализировать строку с помощью XDocument . Синтаксический анализ (строка) вместо получения xml из файла.

3. нет, у меня есть oracle DB, откуда я должен получать свои данные.

4. Откуда берутся данные?

5. DataTable dt = new DataTable(); DataSet ds = new DataSet(); dt = GetRecordDetails() GetRecordDetails получает данные из базы данных oracle