2016-05-19 3 views
0

Это моя структура ответ, который я получаюXSLT для преобразования XML в другую структуру

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
    <s:Body> 
     <GetPrice_HotelResponse xmlns="PricingAirAPI"> 
      <GetPrice_HotelResult xmlns:a="PricingHotelAPI" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
       <a:Error i:nil="true" /> 
       <a:Results xmlns:b="PricingCommonAPI"> 
        <b:HotelSearchResult> 
         <b:AmountAfterTax>561.9600</b:AmountAfterTax> 
         <b:AmountBeforeTax>561.9600</b:AmountBeforeTax> 
         <b:B2B2BHotelPrice xmlns:c="http://schemas.datacontract.org/2004/07/HotelB2B2BPricingEngine"> 
          <c:AgentMarkUp>0</c:AgentMarkUp> 
          <c:SubAgentMarkUp>0</c:SubAgentMarkUp> 
         </b:B2B2BHotelPrice> 
         <b:BookingSource>JacTravel</b:BookingSource> 
         <b:CityId i:nil="true" /> 
         <b:CityName i:nil="true" /> 
         <b:CountryCode i:nil="true" /> 
         <b:Currency>GBP</b:Currency> 
         <b:Discount>0.00</b:Discount> 
         <b:HotelCode>12035</b:HotelCode> 
         <b:HotelName i:nil="true" /> 
         <b:HotelSupplierResultType>None</b:HotelSupplierResultType> 
         <b:IsUniversalApiResult>true</b:IsUniversalApiResult> 
         <b:Price xmlns:c="http://schemas.datacontract.org/2004/07/TekTravel.Hotel.PricingEngine"> 
          <b:AccPriceType>NetFare</b:AccPriceType> 
          <b:AdditionalTxnFee>0.0</b:AdditionalTxnFee> 
          <b:AgentCommission>0</b:AgentCommission> 
          <b:AgentCommissionRate>0</b:AgentCommissionRate> 
          <b:AgentIncentiveAmt>0.00</b:AgentIncentiveAmt> 
          <b:AgentIncentiveRate>0.00</b:AgentIncentiveRate> 
          <b:AgentMarkUp>0</b:AgentMarkUp> 
          <b:AgentMarkUpAmt>0.0000</b:AgentMarkUpAmt> 
          <b:AgentMarkUpType>Percentage</b:AgentMarkUpType> 
          <b:AgentPLB>0</b:AgentPLB> 
          <b:AgentPLBRate>0</b:AgentPLBRate> 
          <b:AirlineBaggageCharges>0</b:AirlineBaggageCharges> 
          <b:AirlineMealCharges>0</b:AirlineMealCharges> 
          <b:AirlineSeatCharges>0</b:AirlineSeatCharges> 
          <b:AirlineTransFee>0</b:AirlineTransFee> 
          <b:CateringCharge>0</b:CateringCharge> 
          <b:CessTax>0</b:CessTax> 
          <b:ChargeBU /> 
          <b:CommissionType>RB</b:CommissionType> 
          <b:ConvenienceCharges>0</b:ConvenienceCharges> 
          <b:Currency /> 
          <b:CurrencyCode>INR</b:CurrencyCode> 
          <b:DealId>0</b:DealId> 
          <b:Discount>0</b:Discount> 
          <b:EduCessAmount>0</b:EduCessAmount> 
          <b:EduCessRate>0</b:EduCessRate> 
          <b:FareBreakdown i:nil="true" /> 
          <b:IsGPEnabled>false</b:IsGPEnabled> 
          <b:IsOurServiceTaxOnBaseFarePlusYQ>false</b:IsOurServiceTaxOnBaseFarePlusYQ> 
          <b:IsOurServiceTaxOnComm>false</b:IsOurServiceTaxOnComm> 
          <b:IsServiceChargeApplicable>true</b:IsServiceChargeApplicable> 
          <b:IsServiceTaxOnBaseFarePlusYQ>false</b:IsServiceTaxOnBaseFarePlusYQ> 
          <b:Markup>80</b:Markup> 
          <b:NetFare>0</b:NetFare> 
          <b:OtherCharge>0</b:OtherCharge> 
          <b:OurCommRate>0</b:OurCommRate> 
          <b:OurCommission>0</b:OurCommission> 
          <b:OurCommissionType>RB</b:OurCommissionType> 
          <b:OurEduCessAmt>0</b:OurEduCessAmt> 
          <b:OurEduCessRate>0</b:OurEduCessRate> 
          <b:OurIncentiveAmt>0</b:OurIncentiveAmt> 
          <b:OurIncentiveRate>0</b:OurIncentiveRate> 
          <b:OurPLB>0</b:OurPLB> 
          <b:OurPLBRate>0</b:OurPLBRate> 
          <b:OurPlbType i:nil="true" /> 
          <b:OurServiceTaxAmt>0</b:OurServiceTaxAmt> 
          <b:OurServiceTaxRate>0</b:OurServiceTaxRate> 
          <b:OurTdsCommAmt>0</b:OurTdsCommAmt> 
          <b:OurTdsIncentiveAmt>0.0</b:OurTdsIncentiveAmt> 
          <b:OurTdsPLBAmt>0</b:OurTdsPLBAmt> 
          <b:OurTdsRate>0</b:OurTdsRate> 
          <b:PlbType i:nil="true" /> 
          <b:PrfCurrency i:nil="true" /> 
          <b:PrfROE>0.0</b:PrfROE> 
          <b:PriceId>0</b:PriceId> 
          <b:PublishedFare>0</b:PublishedFare> 
          <b:RateOfExchange>1</b:RateOfExchange> 
          <b:ResultId>0</b:ResultId> 
          <b:ReverseHandlingCharge>0</b:ReverseHandlingCharge> 
          <b:SegmentFee>0</b:SegmentFee> 
          <b:ServiceTaxRate>0</b:ServiceTaxRate> 
          <b:SeviceTax>0</b:SeviceTax> 
          <b:StockType /> 
          <b:SupplierId>0</b:SupplierId> 
          <b:TDSPLB>0</b:TDSPLB> 
          <b:Tax>0</b:Tax> 
          <b:TaxBreakup i:nil="true" xmlns:d="http://schemas.datacontract.org/2004/07/System.Collections.Generic" /> 
          <b:TdsCommission>0</b:TdsCommission> 
          <b:TdsIncentive>0.00</b:TdsIncentive> 
          <b:TdsRate>0</b:TdsRate> 
          <b:TotalGP>0</b:TotalGP> 
          <b:TransactionFee>0</b:TransactionFee> 
          <b:WLCharge>0</b:WLCharge> 
          <b:WLPrice i:nil="true" /> 
          <b:WhiteLabelDiscount>0</b:WhiteLabelDiscount> 
          <b:YQTax>0</b:YQTax> 
          <c:DynamicPriceAgentComm>0</c:DynamicPriceAgentComm> 
          <c:DynamicPriceOurComm>0</c:DynamicPriceOurComm> 
         </b:Price> 
         <b:RateType>Negotiated</b:RateType> 
         <b:RoomDetails /> 
         <b:TotalGP>0</b:TotalGP> 
        </b:HotelSearchResult> 
        <b:HotelSearchResult> 
         ..... 
        </b:HotelSearchResult> 
       </a:Results> 
       <a:Status>Successful</a:Status> 
       <a:TraceId>b748e818-5c6a-4e41-94ca-f8552a328b99</a:TraceId> 
      </GetPrice_HotelResult> 
     </GetPrice_HotelResponse> 
    </s:Body> 
</s:Envelope> 

Теперь я хочу создать XML как

<?xml version="1.0" encoding="utf-16"?> 
<ArrayOfHotelSearchResult xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <HotelSearchResult> 
    <ResultIndex>1</ResultIndex> 
    <HotelCode>AMB3|LON</HotelCode> 
    <HotelName>Ambassadors Bloomsbury</HotelName> 
    <HotelCategory /> 
    <StarRating>FourStar</StarRating> 
    <HotelDescription>***Special Offer Free welcome gift for stays of 4 or more nights and free bottle of water in each room </HotelDescription> 
    <HotelPromotion /> 
    <HotelPolicy /> 
    <HotelPicture>http://images.gta-travel.com/HH/Images/GB/LON/LON-AMB3-1.jpg</HotelPicture> 
    <HotelAddress>12 UPPER WOBURN PLACE London WC1 0HX United Kingdom, , United Kingdom, </HotelAddress> 
    <HotelContactNo /> 
    <Latitude /> 
    <Longitude /> 
    <AmountBeforeTax>0</AmountBeforeTax> 
    <AmountAfterTax>0</AmountAfterTax> 
    <AmountBeforeDiscount>0</AmountBeforeDiscount> 
    <AmountBeforeTaxInSupplierCurr>259.00</AmountBeforeTaxInSupplierCurr> 
    <AmountAfterTaxInSupplierCurr>259.00</AmountAfterTaxInSupplierCurr> 
    <AmountBeforeDiscountInSupplierCurr>259.00</AmountBeforeDiscountInSupplierCurr> 
    <BookingSource>GTA</BookingSource> 
    <CurrencySupplier>GBP</CurrencySupplier> 
    <PreferredROE>0</PreferredROE> 
    <IsBaseCurrencyRequired>false</IsBaseCurrencyRequired> 
    <Price> 
     <CommissionType>RB</CommissionType> 
     <PlbType>RB</PlbType> 
     <OurPlbType>RB</OurPlbType> 
     <AirlineTransFee>0</AirlineTransFee> 
     <TdsCommission>0</TdsCommission> 
     <TDSPLB>0</TDSPLB> 
     <PriceId>0</PriceId> 
     <PublishedFare>0</PublishedFare> 
     <NetFare>0</NetFare> 
     <Markup>0</Markup> 
     <ServiceTax>0</ServiceTax> 
     <CessTax>0</CessTax> 
     <OurCommission>0</OurCommission> 
     <OurPLB>0</OurPLB> 
     <AgentCommission>0</AgentCommission> 
     <AgentPLB>0</AgentPLB> 
     <OtherCharges>0</OtherCharges> 
     <Tax>0</Tax> 
     <WhiteLabelDiscount>0</WhiteLabelDiscount> 
     <TransactionFee>0</TransactionFee> 
     <Currency>INR</Currency> 
     <ChargeBU /> 
     <AccPriceType>PublishedFare</AccPriceType> 
     <RateOfExchange>0</RateOfExchange> 
     <AdditionalTxnFee>0</AdditionalTxnFee> 
     <WLCharge>0</WLCharge> 
     <Discount>0</Discount> 
     <ReverseHandlingCharge>0</ReverseHandlingCharge> 
     <YQTax>0</YQTax> 
     <IsServiceTaxOnBaseFarePlusYQ>false</IsServiceTaxOnBaseFarePlusYQ> 
     <TdsRate>0</TdsRate> 
     <AgentMarkUpType>Percentage</AgentMarkUpType> 
     <AgentMarkUp>0</AgentMarkUp> 
     <AgentMarkUpAmt>0</AgentMarkUpAmt> 
     <ConvenienceCharges>0</ConvenienceCharges> 
     <PrfROE>0</PrfROE> 
     <ServiceTaxRate>0</ServiceTaxRate> 
     <EduCessRate>0</EduCessRate> 
     <EduCessAmount>0</EduCessAmount> 
     <AgentCommissionRate>0</AgentCommissionRate> 
     <AgentPLBRate>0</AgentPLBRate> 
     <AirlineBaggageCharges>0</AirlineBaggageCharges> 
     <AirlineMealCharges>0</AirlineMealCharges> 
     <AirlineSeatCharges>0</AirlineSeatCharges> 
     <OurCommRate>0</OurCommRate> 
     <OurPLBRate>0</OurPLBRate> 
     <OurIncentiveRate>0</OurIncentiveRate> 
     <OurIncentiveAmt>0</OurIncentiveAmt> 
     <SegmentFee>0</SegmentFee> 
     <OurCommissionType>RB</OurCommissionType> 
     <OurServiceTaxRate>0</OurServiceTaxRate> 
     <OurServiceTaxAmt>0</OurServiceTaxAmt> 
     <OurEduCessRate>0</OurEduCessRate> 
     <OurEduCessAmt>0</OurEduCessAmt> 
     <OurTdsRate>0</OurTdsRate> 
     <IsServiceChargeApplicable>true</IsServiceChargeApplicable> 
     <OurTdsCommAmt>0</OurTdsCommAmt> 
     <OurTdsPLBAmt>0</OurTdsPLBAmt> 
     <IsGPEnabled>false</IsGPEnabled> 
     <TotalGP>0</TotalGP> 
     <CateringCharge>0</CateringCharge> 
     <AgentIncentiveRate>0.00</AgentIncentiveRate> 
     <AgentIncentiveAmt>0.00</AgentIncentiveAmt> 
     <TdsIncentive>0.00</TdsIncentive> 
     <DealId>0</DealId> 
     <SupplierId>0</SupplierId> 
     <StockType /> 
     <IsPaidByAgentCreditCard>false</IsPaidByAgentCreditCard> 
     <AmountPaidByAgentCreditCard>0.00</AmountPaidByAgentCreditCard> 
     <OurTdsIncentiveAmt>0.00</OurTdsIncentiveAmt> 
     <IsOurServiceTaxOnComm>false</IsOurServiceTaxOnComm> 
     <IsOurServiceTaxOnBaseFarePlusYQ>false</IsOurServiceTaxOnBaseFarePlusYQ> 
     <ServiceFee>0</ServiceFee> 
     <TotalTxnFee>0</TotalTxnFee> 
     <SwachhBharatCessRate>0</SwachhBharatCessRate> 
     <SwachhBharatCessAmount>0</SwachhBharatCessAmount> 
    </Price> 
    <RateType>Negotiated</RateType> 
    <CityName /> 
    <IsDomestic>false</IsDomestic> 
    <NoOfRooms>0</NoOfRooms> 
    <NoOfNights>0</NoOfNights> 
    <IsTBOMapped>false</IsTBOMapped> 
    <SupplierHotelCodes /> 
    <UAPISessionId>7685eeea-c903-4eb7-ae76-2369f40b635c</UAPISessionId> 
    <HotelDetails> 
     <StarRating>All</StarRating> 
    </HotelDetails> 
    <BookingMode>NotSet</BookingMode> 
    </HotelSearchResult> 
    <HotelSearchResult> 
    ....... 
    </HotelSearchResult> 
</ArrayOfHotelSearchResult> 

Может кто-нибудь помочь мне в создании XSLT. В настоящее время я не могу получить какое-либо значение в xslt, и я также сталкиваюсь с проблемой при отладке в VS2012. Иногда отладчик иногда приходит.

+1

Просьба представить пример таблицы стилей. Здесь есть куча пространства имен, возможно, это связано с ... – potame

ответ

-1

XSLT - это тип таблицы стилей, в основном используемый для представления данных из XML в удобном для восприятия человеком способом, обычно путем помещения его в HTML-элементы.

Если вы хотите преобразовать существующий XML в новую структуру, я предлагаю вам использовать XML-инструменты на C# для десериализации XML, сопоставления его с новой структурой и визуализации нового XML.

+0

XSLT может использоваться для преобразования XML в другую структуру. Он специально не используется для обеспечения его удобочитаемой версии - даже если это наиболее распространенное использование. – potame

+0

Конечно, HTML - это XML. Прости. что ты уже испробовал? Пожалуйста, обновите вопрос с помощью образца xslt. – Puppetmupp

+0

Боюсь, что вы не ошиблись. XSLT - это язык, разработанный специально для преобразования XML из одной схемы в другую, а также в HTML и обычный текст. И, по крайней мере, по моему опыту, наиболее распространенным моментом является переход между двумя системами - без учета удобочитаемости человека, кроме как в качестве бонуса. (И нет, HTML не XML.) –

0

Вот начало использования XML LINQ

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication93 
{ 
    class Program 
    { 
     const string XML_INPUT = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument inputDoc = XDocument.Load(XML_INPUT); 
      List<XElement> hotelSearchResults = inputDoc.Descendants().Where(x => x.Name.LocalName == "HotelSearchResult").ToList(); 
      XNamespace aNS = hotelSearchResults[0].GetNamespaceOfPrefix("a"); 
      XNamespace bNS = hotelSearchResults[0].GetNamespaceOfPrefix("b"); 

      string header = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + 
       "<ArrayOfHotelSearchResult xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + 
       "</ArrayOfHotelSearchResult>"; 


      XDocument doc = XDocument.Parse(header); 
      XElement arrayOfHotelSearchResult = (XElement)doc.FirstNode; 
      int count = 0; 
      foreach (XElement hotelSearchResult in hotelSearchResults) 
      { 
       XElement newHotel = new XElement("HotelSearchResult"); 
       arrayOfHotelSearchResult.Add(newHotel); 
       newHotel.Add(new object[] { 
        new XElement("ResultIndex", ++count), 
        new XElement("HotelCode", (string)hotelSearchResult.Descendants(bNS + "HotelCode").FirstOrDefault()) 
       }); 
       XElement price = new XElement("Price"); 
       newHotel.Add(price); 
       price.Add(new XElement("CommissionType", (string)hotelSearchResult.Descendants(bNS + "CommissionType").FirstOrDefault())); 
      } 
     } 
    } 

} 

Использование XmlReader

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication93 
{ 
    class Program 
    { 
     const string XML_INPUT = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XmlReader reader = XmlReader.Create(XML_INPUT); 
      XNamespace bNS = "PricingCommonAPI"; 
      while(!reader.EOF) 
      { 
       if(reader.Name != "HotelSearchResult") 
       { 
        reader.ReadToFollowing("HotelSearchResult", bNS.NamespaceName); 
       } 
       if(!reader.EOF) 
       { 
        XElement hotelSearchResult = (XElement)XElement.ReadFrom(reader); 
       } 
      } 
     } 
    } 

} 
+0

Привет, я уже использую аналогичный код, который отлично работает, но мой размер xml слишком высок, иногда вокруг (6-8 мб), поэтому XDocument.Load (XML_INPUT) занимает слишком много времени в таком сценарии. Я обнаружил, что xslt намного быстрее в таких случаях. Вот почему я хочу сделать это с помощью xslt. – Rohit

+0

Для огромных файлов xml вам нужно использовать XmlReader. Я добавил дополнительный код в мое сообщение о том, как использовать XmlReader с Linq. – jdweng

Смежные вопросы