(部分)我使用的对象的矩阵表示如下:
{
{1, A,{100, 20, 30},10},
{2, B,{100}, 0},
{3, X,{120,20},0},
{4, C,{},11}
}
我想以XML格式将这些数据存储在外部,如下所示
<数据>
< row key =“1”val1 =“A”val2 =“10”> < OCC> 100℃; / OCC>< OCC> 20℃/ OCC>< OCC> 30℃; / OCC>< /排>
< row key =“2”val1 =“B”val2 =“0”>< occ> 100< / occ>< / row>
< row key =“3”val1 =“X”val2 =“0”>< occ> 120< / occ>< occ> 20< / occ>< / row>
< row key =“4”val1 =“C”val2 =“11”>< / row>
< /数据>
我正在寻找一个如何:
的例子答案 0 :(得分:5)
这里我们将您的数据导入为符号XML:
In[50]:= xml = Import["C:\\Temp\\matrixData.xml"]
Out[50]= XMLObject["Document"][{},
XMLElement["data", {},
{XMLElement["row", {"key" -> "1", "val1" -> "A", "val2" -> "10"},
{XMLElement["occ", {}, {"100"}], XMLElement["occ", {}, {"20"}],
XMLElement["occ", {}, {"30"}]}],
XMLElement["row", {"key" -> "2", "val1" -> "B", "val2" -> "0"},
{XMLElement["occ", {}, {"100"}]}],
XMLElement[ "row", {"key" -> "3", "val1" -> "X","val2" -> "0"},
{XMLElement["occ", {}, {"120"}], XMLElement["occ", {}, {"20"}]}],
XMLElement["row", {"key" -> "4", "val1" -> "C", "val2" -> "11"}, {}]}], {}]
我们在这里解析矩阵:
In[51]:= matr =
xml /. XMLObject["Document"][{}, data_, _] :> data /.
XMLElement["data", _, children_] :> children /.
XMLElement["row", attrs_, vals_] :> {"key" /. attrs,
"val1" /. attrs, vals /. XMLElement["occ", _, {val_}] :> val,
"val2" /. attrs} /. s_String :> ToExpression[s]
Out[51]= {{1, A, {100, 20, 30}, 10}, {2, B, {100}, 0}, {3,X, {120, 20}, 0}, {4, C, {}, 11}}
由于使用规则规则技术,代码简短且经济。我讨论它here。可以找到这种技术的一个很好的应用here。
这是相反的:
XMLObject["Document"][{}, XMLElement["data", {},
Replace[matr, {key_, val1_, vals_List, val2_} :>
XMLElement[ "row", {"key" -> ToString[key], "val1" -> ToString[val1],
"val2" -> ToString[val2]},
XMLElement["occ", {}, {ToString[#]}] & /@ vals], {1}]], {}]
我没有显示结果,但它与导入的符号XML相同。您可以使用此符号XML调用Export
,它将知道如何处理它。