jjzjj

c# - 将 XML 数据转换为任何 XML 响应的 tsql 记录

coder 2024-06-24 原文

我不知道它是否已经得到回答,但我的运气不好,所以我无法用我的狩猎技术在 stackoverflow 的任何地方找到它。请忽略我的垃圾邮件

我们有一个要求,我们需要编写一个 API 解析器,该解析器适用于任何提供 XML 输出的 API。

我们事先不知道 XML 结构。

解决方案应转换 XML 文件并将其保存在通用 tsql 表中,其中 XML 元素/属性名称作为第一行。

所以基本上它是任何 API 的 XML 反序列化器。

我们不能为我们的 C# 类使用任何第三方 dll。

我对 C# 一无所知,所以不知道它是否可行。但是我已经能够使用 OPENXML 在 tsql 中编写一个通用的 XML-> 行转换器。 tsql 解决方案的问题是我们无法将巨大的 XML 文件成功导入数据库。

我可以提供所需的任何详细信息。请在评论/回答中让我知道。

我不希望任何人为我写代码,任何合适的指针就足够了

资源: JSON

[
{
        "id" : 21953,
        "mainReqIdentity" : "xxxx",
        "itemName" : "xxxx",
        "kanbanPhase" : "xxxx",
        "kanbanStatus" : "xxxx",
        "backlogItemType" : "xxxx",
        "identityDomain" : "xxxx",
        "fromDatetime" : "2016-08-05 17:52:34",
        "teams" : [],
        "releases" : [{
                "id" : 1229,
                "release_name" : "xxxx",
                "release_connection_type" : "xxxx"
            }
        ],
        "fpReleases" : [],
        "sources" : [{
                "sourceName" : "xxxx",
                "sourceRecordUrl" : "xxxx",
                "sourceRecordIdentity" : "xxxx"
            }
        ],
        "productNumbers" : [],
        "tags" : [],
        "productComponents" : [],
        "ranPlatforms" : [],
        "subReleases" : [],
        "requirementAreaId" : xxxx,
        "requirementArea" : "xxxx",
        "toBeHandledAtxxxx" : "xxxx"
    }, {
        "id" : 22014,
        "mainReqIdentity" : "xxxx",
        "itemName" : "xxxx",
        "kanbanPhase" : "xxxx",
        "kanbanStatus" : "xxxx",
        "backlogItemType" : "xxxx",
        "identityDomain" : "xxxx",
        "fromDatetime" : "2016-08-05 17:52:34",
        "teams" : [],
        "releases" : [{
                "id" : xxxx,
                "release_name" : "xxxx",
                "release_connection_type" : "xxxx"
            }
        ],
        "fpReleases" : [],
        "sources" : [{
                "sourceName" : "xxxx",
                "sourceRecordUrl" : "xxxx",
                "sourceRecordIdentity" : "xxxx"
            }
        ],
        "productNumbers" : [],
        "tags" : [],
        "productComponents" : [],
        "ranPlatforms" : [],
        "subReleases" : [],
        "requirementAreaId" : xxxx,
        "requirementArea" : "xxxx",
        "f0Date" : "2015-10-01",
        "f1Date" : "2015-10-01",
        "f2Date" : "2016-02-01",
        "f4Date" : "2016-03-31",
        "fgDate" : "2016-04-29",
        "toBeHandledAtxxxx" : "xxxx"
    }
    ]

XML:2 个样本

示例 1

    <root type="array">
    <id type="number">21286</id>
    <mainReqIdentity type="string">xxxxxx</mainReqIdentity>
    <itemName type="string">xxxxxx</itemName>
    <kanbanPhase type="string">xxxxxx</kanbanPhase>
    <kanbanStatus type="string">xxxxxx</kanbanStatus>
    <kanbanNote type="string">xxxxxx</kanbanNote>
    <backlogItemType type="string">xxxxxx</backlogItemType>
    <identityDomain type="string">xxxxxx</identityDomain>
    <fromDatetime type="string">2016-08-23 17:01:52</fromDatetime>
    <teams type="array">
      <item type="object">
        <team_name type="string">xxxxxx</team_name>
        <preliminary type="boolean">xxxxxx</preliminary>
      </item>
    </teams>
    <releases type="array">
      <item type="object">
        <id type="number">xxxxxx</id>
        <release_name type="string">xxxxxx</release_name>
        <release_connection_type type="string">xxxxxx</release_connection_type>
      </item>
    </releases>
    <fpReleases type="array">
    </fpReleases>
    <sources type="array">
      <item type="object">
        <sourceName type="string">xxxxxx</sourceName>
        <sourceRecordUrl type="string">xxxxxx</sourceRecordUrl>
      </item>
    </sources>
    <productNumbers type="array">
    </productNumbers>
    <tags type="array">
    </tags>
    <productComponents type="array">
    </productComponents>
    <ranPlatforms type="array">
    </ranPlatforms>
    <subReleases type="array">
    </subReleases>
    <requirementAreaId type="number">xxxxxx</requirementAreaId>
    <requirementArea type="string">xxxxxx</requirementArea>
    <itemContact type="string">xxxxxx</itemContact>
    <toBeHandledAtxxx type="string">xxxxxx</toBeHandledAtLuca>
  </item>
    <item type="object">
    <id type="number">xxxxxx</id>
    <mainReqIdentity type="string">xxxxxx</mainReqIdentity>
    <itemName type="string">xxxxxx</itemName>
    <kanbanPhase type="string">xxxxxx</kanbanPhase>
    <kanbanStatus type="string">xxxxxx</kanbanStatus>
    <kanbanNote type="string">xxxxxx</kanbanNote>
    <backlogItemType type="string">xxxxxx</backlogItemType>
    <identityDomain type="string">xxxxxx</identityDomain>
    <fromDatetime type="string">2016-08-23 17:01:52</fromDatetime>
    <teams type="array">
      <item type="object">
        <team_name type="string">xxxxxx</team_name>
        <preliminary type="boolean">xxxxxx</preliminary>
      </item>
    </teams>
    <releases type="array">
      <item type="object">
        <id type="number">xxxxxx</id>
        <release_name type="string">xxxxxx</release_name>
        <release_connection_type type="string">xxxxxx</release_connection_type>
      </item>
    </releases>
    <fpReleases type="array">
    </fpReleases>
    <sources type="array">
      <item type="object">
        <sourceName type="string">xxxxxx</sourceName>
        <sourceRecordUrl type="string">xxxxxx</sourceRecordUrl>
      </item>
    </sources>
    <productNumbers type="array">
    </productNumbers>
    <tags type="array">
    </tags>
    <productComponents type="array">
    </productComponents>
    <ranPlatforms type="array">
    </ranPlatforms>
    <subReleases type="array">
    </subReleases>
    <requirementAreaId type="number">xxxxxx</requirementAreaId>
    <requirementArea type="string">xxxxxx</requirementArea>
    <oaResultReference type="string">xxxxxx</oaResultReference>
    <itemContact type="string">xxxxxx</itemContact>
    <f0Date type="string">2014-10-17</f0Date>
    <f1Date type="string">2015-01-16</f1Date>
    <f2Date type="string">2015-02-13</f2Date>
    <f4Date type="string">2015-06-12</f4Date>
    <faDate type="string">2015-06-12</faDate>
    <fgDate type="string">2015-06-12</fgDate>
    <toBeHandledAtxxx type="string">xxxxxx</toBeHandledAtLuca>
  </item>
 </root>

示例 2

<ROOT>  
<Customer CustomerID="VINET" ContactName="Paul Henriot">  
   <Order CustomerID="VINET" EmployeeID="5" OrderDate="1996-07-04T00:00:00">  
      <OrderDetail OrderID="10248" ProductID="11" Quantity="12"/>  
      <OrderDetail OrderID="10248" ProductID="42" Quantity="10"/>  
   </Order>  
</Customer>  
<Customer CustomerID="LILAS" ContactName="Carlos Gonzlez">  
   <Order CustomerID="LILAS" EmployeeID="3" OrderDate="1996-08-16T00:00:00">  
      <OrderDetail OrderID="10283" ProductID="72" Quantity="3"/>  
   </Order>  
</Customer>  
</ROOT>

SQL

通用暂存表

create table ZZZZZZZZZ
(
api_id int,
record_type char(1),
record_id INT,
last_run_time datetime,
last_run_by varchar(500),
col1 VARCHAR(500),
col2 VARCHAR(500),
col3 VARCHAR(500),
col4 VARCHAR(500),
col5 VARCHAR(500),
col6 VARCHAR(500),
col7 VARCHAR(500),
col8 VARCHAR(500),
col9 VARCHAR(500),
col10 VARCHAR(500),
col11 VARCHAR(500),
col12 VARCHAR(500),
col13 VARCHAR(500),
col14 VARCHAR(500),
col15 VARCHAR(500),
col16 VARCHAR(500),
col17 VARCHAR(500),
col18 VARCHAR(500),
col19 VARCHAR(500),
col20 VARCHAR(500),
col21 VARCHAR(500),
col22 VARCHAR(500),
col23 VARCHAR(500),
col24 VARCHAR(500),
col25 VARCHAR(500),
col26 VARCHAR(500),
col27 VARCHAR(500),
col28 VARCHAR(500),
col29 VARCHAR(500),
col30 VARCHAR(500),
col31 VARCHAR(500),
col32 VARCHAR(500),
col33 VARCHAR(500),
col34 VARCHAR(500),
col35 VARCHAR(500),
col36 VARCHAR(500),
col37 VARCHAR(500),
col38 VARCHAR(500),
col39 VARCHAR(500),
col40 VARCHAR(500),
col41 VARCHAR(500),
col42 VARCHAR(500),
col43 VARCHAR(500),
col44 VARCHAR(500),
col45 VARCHAR(500),
col46 VARCHAR(500),
col47 VARCHAR(500),
col48 VARCHAR(500),
col49 VARCHAR(500),
col50 VARCHAR(500),
col51 VARCHAR(500),
col52 VARCHAR(500),
col53 VARCHAR(500),
col54 VARCHAR(500),
col55 VARCHAR(500),
col56 VARCHAR(500),
col57 VARCHAR(500),
col58 VARCHAR(500),
col59 VARCHAR(500),
col60 VARCHAR(500),
col61 VARCHAR(500),
col62 VARCHAR(500),
col63 VARCHAR(500),
col64 VARCHAR(500),
col65 VARCHAR(500),
col66 VARCHAR(500),
col67 VARCHAR(500),
col68 VARCHAR(500),
col69 VARCHAR(500),
col70 VARCHAR(500),
col71 VARCHAR(500),
col72 VARCHAR(500),
col73 VARCHAR(500),
col74 VARCHAR(500),
col75 VARCHAR(500),
col76 VARCHAR(500),
col77 VARCHAR(500),
col78 VARCHAR(500),
col79 VARCHAR(500),
col80 VARCHAR(500),
col81 VARCHAR(500),
col82 VARCHAR(500),
col83 VARCHAR(500),
col84 VARCHAR(500),
col85 VARCHAR(500),
col86 VARCHAR(500),
col87 VARCHAR(500),
col88 VARCHAR(500),
col89 VARCHAR(500),
col90 VARCHAR(500),
col91 VARCHAR(500),
col92 VARCHAR(500),
col93 VARCHAR(500),
col94 VARCHAR(500),
col95 VARCHAR(500),
col96 VARCHAR(500),
col97 VARCHAR(500),
col98 VARCHAR(500),
col99 VARCHAR(500),
col100 VARCHAR(500),
col101 VARCHAR(500),
col102 VARCHAR(500),
col103 VARCHAR(500),
col104 VARCHAR(500),
col105 VARCHAR(500),
col106 VARCHAR(500),
col107 VARCHAR(500),
col108 VARCHAR(500),
col109 VARCHAR(500),
col110 VARCHAR(500),
col111 VARCHAR(500),
col112 VARCHAR(500),
col113 VARCHAR(500),
col114 VARCHAR(500),
col115 VARCHAR(500),
col116 VARCHAR(500),
col117 VARCHAR(500),
col118 VARCHAR(500),
col119 VARCHAR(500),
col120 VARCHAR(500),
col121 VARCHAR(500),
col122 VARCHAR(500),
col123 VARCHAR(500),
col124 VARCHAR(500),
col125 VARCHAR(500),
col126 VARCHAR(500),
col127 VARCHAR(500),
col128 VARCHAR(500),
col129 VARCHAR(500),
col130 VARCHAR(500),
col131 VARCHAR(500),
col132 VARCHAR(500),
col133 VARCHAR(500),
col134 VARCHAR(500),
col135 VARCHAR(500),
col136 VARCHAR(500),
col137 VARCHAR(500),
col138 VARCHAR(500),
col139 VARCHAR(500),
col140 VARCHAR(500),
col141 VARCHAR(500),
col142 VARCHAR(500),
col143 VARCHAR(500),
col144 VARCHAR(500),
col145 VARCHAR(500),
col146 VARCHAR(500),
col147 VARCHAR(500),
col148 VARCHAR(500),
col149 VARCHAR(500),
col150 VARCHAR(500)
)

示例输出

用 TSQL 编写的通用 XML 解析器。代码中几乎没有 hack 和一些需要删除的杂散代码。这很好用。但问题在于通过直接调用或通过文件将整个 XML 文档作为输入参数从 C# 代码发送。

CREATE PROC ZZZZZZZ
(
@in_api_id int,
@in_xml_doc XML,
@in_xml_root varchar(100),
@in_tot_result_col int = 150,
@in_need_colnm_result CHAR(1) = 'Y',
@in_debug_flg CHAR(1) = 'N'
)
AS
BEGIN
DECLARE 
    @idoc int, 
    @sqlstr nvarchar(max) = '',
    @param nvarchar(200) = '',
    @runtime datetime = getdate(),
    @runby varchar(30) = suser_name(),
    @cnt int,
    @pre_stg_col_nm varchar(max) = '',
    @max_lvl int,
    @max_node varchar(500)='',
    @max_node_wo_slash varchar(500)='',
    @xml_col nvarchar(max) = '',
    @unq_col nvarchar(max) = '',
    @unq_xml_col nvarchar(max)=''

--Create an internal representation of the XML document.  
EXEC sp_xml_preparedocument @idoc OUTPUT, @in_xml_doc;  
-- Execute a SELECT statement that uses the OPENXML rowset provider.  
set @in_xml_root = concat('/',@in_xml_root)
SELECT * into #tmp FROM OPENXML (@idoc, @in_xml_root,2) where id <> 0;

--select * from #tmp_xml_nodes
--select * from #tmp
--select * from #tmp_pre_staging

;with xml_cte(id, parentid, nodetype, localname, prefix, namespaceuri, datatype, prev, text, lvl,node,parent_localname)
AS
(
select  id, 
                parentid, 
                nodetype, 
                localname, 
                prefix, 
                namespaceuri, 
                datatype, 
                prev, 
                text,
                1 as lvl,
                cast(CONCAT(@in_xml_root,'/',localname) as varchar(100)) node,
                cast('' as varchar(200))
from #tmp
where parentid = 0
UNION all
select  t.id, 
                t.parentid, 
                t.nodetype, 
                t.localname, 
                t.prefix, 
                t.namespaceuri, 
                t.datatype, 
                t.prev, 
                t.text,
                iif(t.nodetype = 1,xc.lvl+1,xc.lvl),
                cast(
                        CONCAT (
                                        xc.node
                                        ,iif(t.nodetype = 1, 
                                                CONCAT (
                                                            '/'
                                                            ,t.localname
                                                            )
                                                ,''
                                                )
                                        ) AS VARCHAR(100)
                            ),
                cast(xc.localname as varchar(200))
from #tmp t
inner join xml_cte xc
on xc.id = t.parentid
)
select * into #xmlcte from xml_cte

--select * from #xmlcte
--v2 change
select @max_lvl = max(lvl)--iif(max(lvl)>=4,1,0) -- the iif condition is just a hack, I dont know why it works
from #xmlcte 

select 
    @max_node = concat(max(node),'/'),
    @max_node_wo_slash = max(node) 
from #xmlcte 
where lvl = @max_lvl

select *,concat(parent_localname,'_',localname,' varchar(500)') fnl_col_nm,
                                case 
                                when lvl<@max_lvl then concat(replicate('../',@max_lvl-lvl+iif(nodetype=1,nodetype,0)),iif(nodetype=1,'','@'),localname) --v2 change
                                when lvl>@max_lvl then concat(replace(node,@max_node,''),iif(nodetype=1,'','/@'),localname)--v2 change
                                else concat('../',iif(nodetype=1,'',concat(parent_localname,'/@')),localname)--v2 change
                                end col_Struct
        ,concat(parent_localname,'_',localname) col_unq_nm
        ,ROW_NUMBER() over (order by(select 100)) sno
        ,concat('xmlname.value(''/Names[1]/name[',ROW_NUMBER() over (order by(select 100)),']'',''varchar(500)'') AS ',concat(parent_localname,'_',localname)) col_splt_nm
into #xml_col_struct
from #xmlcte
where nodetype <= 2--v2 change

--select * from #xml_col_struct
set @cnt = (select count(distinct col_unq_nm) from #xml_col_struct)

select @pre_stg_col_nm =
(
select concat(',',COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'ZZZZZZ'
and COLUMN_NAME like 'col%'
and ORDINAL_POSITION <= @cnt+5
order by ORDINAL_POSITION
for xml path('')
)

set @sqlstr = concat(
                                        'insert into ZZZZZ(api_id,record_type,record_id,last_run_time,last_run_by',
                                        @pre_stg_col_nm,
                                        ')'
                                        )
select @xml_col =
(
select distinct concat(',',fnl_col_nm,' ''',col_Struct,'''',char(10)) 
from #xml_col_struct
order by 1
for xml path('')
)
set @xml_col = stuff(@xml_col,1,1,'')

select @unq_col =
(
select distinct concat(',',col_unq_nm )
from #xml_col_struct
order by 1
for xml path('')
)
set @unq_col = stuff(@unq_col,1,1,'')

select @in_tot_result_col = @in_tot_result_col - count(distinct col_unq_nm)
from #xml_col_struct

select @unq_xml_col =
(
select 
concat(',xmlname.value(''/Names[1]/name[',ROW_NUMBER() over (order by(select 100)),']'',''varchar(500)'') AS ',col_unq_nm,char(10))
from (select distinct col_unq_nm from #xml_col_struct) t
for xml path('')
)
set @unq_xml_col = stuff(@unq_xml_col,1,1,'')

set @sqlstr =
                        concat(
                                    iif(@in_need_colnm_result = 'Y',
                                    concat('
                                                ;WITH Split_Names (xmlname)
                                                AS
                                                (
                                                        SELECT 
                                                        CONVERT(XML,''<Names><name>''  
                                                        + REPLACE(''',@unq_col,''','','', ''</name><name>'') + ''</name></Names>'') AS xmlname
                                                )
                                                '
                                                --,@sqlstr
                                                ,char(10),
                                                ' SELECT ',@in_api_id,',''H'',0,''',@runtime,''',''',@runby,''',',char(10)
                                                ,@unq_xml_col,replicate(',NULL',@in_tot_result_col)--v2 change
                                                ,char(10)
                                                ,'FROM Split_Names'
                                                ,char(10)
                                                ,'union all'
                                                )
                                        ,''
                                        )
                                    --,iif(@in_need_colnm_result = 'Y','',@sqlstr)
                                    ,'
                                    SELECT ',@in_api_id,',''D'',ROW_NUMBER() over (order by(select 100)),''',@runtime,''',''',@runby,''',*'  
                                    ,replicate(',NULL',@in_tot_result_col)--v2 change
                                    ,char(10)
                                    ,'FROM   OPENXML (@idoc_inn, ''',@max_node_wo_slash,''',2)'   
                                    ,char(10)
                                    ,'WITH (',@xml_col,')'
                                    )

if @in_debug_flg = 'Y'
    begin
        select @max_lvl+1,@max_lvl,@max_node_wo_slash,@xml_col,@unq_col,@sqlstr,@unq_xml_col
        select * from #xml_col_struct--v2 change
    end
else
    begin
        set @param = '@idoc_inn int'
        exec sys.sp_executesql @sqlstr,@param,@idoc_inn = @idoc
    end
EXEC sp_xml_removedocument @idoc

END

读取 C# 类加载的 XML 文件的 SQL 代码。这也可以正常工作,但问题是所有行都在单独的行中,并且连接在一个点之后被截断

create table #tmp(data_line nvarchar(max))

bulk insert #tmp
FROM '\\Server\\ZZZZ\\Downloads\\Data.xml'  
   WITH   
      ( 
                --firstrow = 1          
                 ROWTERMINATOR ='\n'  
      );  

select * from #tmp

C# 类

Object httpConn = Dts.Connections["HTTP"].AcquireConnection(null);
        HttpClientConnection myConnection = new HttpClientConnection(httpConn);
        myConnection.ServerURL = string.Format(("http://xxxx.com/jjjj"),"userid","password");
        byte[] webdata = myConnection.DownloadData();

        String result_data = Convert.ToBase64String(webdata);
        XmlDocument xd = new XmlDocument();
        XmlDictionaryReader xr = JsonReaderWriterFactory.CreateJsonReader(webdata, XmlDictionaryReaderQuotas.Max);

        xr.Read();
        xd.LoadXml(xr.ReadOuterXml());
        xd.Save("\\Server\\ZZZZ\\Downloads\\Data.xml"); 

最佳答案

如果您获得格式正确的 XML。您可以使用数据集。具体使用Dataset.ReadXml()。这将在独立于 xml 标记的 Dataset 对象中加载您的 xml。然后你可以使用 ADO.Net、linq2sql、EF 或任何其他通信方法将其放入数据库中。

因为你在服务器上保存文件,你可以使用下面的代码:

DataSet ds = new DataSet();
ds.ReadXml("\\Server\\ZZZZ\\Downloads\\Data.xml"); 

然后您可以使用 foreach 循环遍历数据集的每个表。 xml 中的属性将成为数据表中的列。

因此您的最终代码将与此类似:

using (DataSet ds = new DataSet())
{
     ds.ReadXml("\\Server\\ZZZZ\\Downloads\\Data.xml");
     int nTableCounts = ds.Tables.Count;
     foreach(DataTable dt in ds.Tables)
     {
          using (dt)
          {
            //Put data in SQL table.
          }
     }
}

如果有任何不清楚的地方,请告诉我。

关于c# - 将 XML 数据转换为任何 XML 响应的 tsql 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40155341/

有关c# - 将 XML 数据转换为任何 XML 响应的 tsql 记录的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. ruby - 使用 ruby​​ 将 HTML 转换为纯文本并维护结构/格式 - 2

    我想将html转换为纯文本。不过,我不想只删除标签,我想智能地保留尽可能多的格式。为插入换行符标签,检测段落并格式化它们等。输入非常简单,通常是格式良好的html(不是整个文档,只是一堆内容,通常没有anchor或图像)。我可以将几个正则表达式放在一起,让我达到80%,但我认为可能有一些现有的解决方案更智能。 最佳答案 首先,不要尝试为此使用正则表达式。很有可能你会想出一个脆弱/脆弱的解决方案,它会随着HTML的变化而崩溃,或者很难管理和维护。您可以使用Nokogiri快速解析HTML并提取文本:require'nokogiri'h

  3. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  4. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  7. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  8. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  9. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  10. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

随机推荐