我遇到的问题是读取XML文件并拉出多个PIECE_WGT。想要拉取属性以及元素值
以下是我遇到以下问题的地方
Pieces = el.Element("PIECE_WGT").Attribute("CNT").Value,
Weight = el.Element("PIECE_WGT").Value
以下是我的所有代码
class FILELOGElements
{
public string FileNo { get; set; }
public string TotPieces { get; set; }
public string TotWeight { get; set; }
public string PiecesUsed { get; set; }
public double Pieces { get; set; }
public double Weight { get; set; }
}
private IEnumerable<FILELOGElements> FileInfo(XElement doc, string FileNo)
{
IEnumerable <FILELOGElements> Info =
from el in doc.Elements("FILE_NO")
where el.Attribute("ID").Value.ToUpper() == FileNo
select new FILELOGElements
{
FileNo = el.Attribute("ID").Value.ToUpper(),
TotPieces = el.Element("TOTAL_PIECES").Value.ToUpper(),
TotWeight = el.Element("TOTAL_WEIGHT").Value.ToUpper(),
PiecesUsed = el.Element("PIECES_USED").Value.ToUpper(),
Pieces = el.Element("PIECE_WGT").Attribute("CNT").Value,
Weight = el.Element("PIECE_WGT").Value
};
return Info;
}
以下是XML文档的设置方法:
<INFO>
<FILE_NO ID="2150510370">
<TOTAL_PIECES>2</TOTAL_PIECES>
<TOTAL_WEIGHT>500</TOTAL_WEIGHT>
<PIECES_USED>2</PIECES_USED>
<PIECE_WGT CNT="1">100</PIECE_WGT>
<PIECE_WGT CNT="2">125</PIECE_WGT>
</FILE_NO>
<FILE_NO ID="2150510371">
<TOTAL_PIECES>10</TOTAL_PIECES>
<TOTAL_WEIGHT>1000</TOTAL_WEIGHT>
<PIECES_USED>3</PIECES_USED>
<PIECE_WGT CNT="1">100</PIECE_WGT>
<PIECE_WGT CNT="2">125</PIECE_WGT>
<PIECE_WGT CNT="3">275</PIECE_WGT>
</FILE_NO>
</INFO>
答案 0 :(得分:0)
不确定这是否是正确的方法,但这是我设法让它工作的方式
我将Pieces and Weights转换为List,以便我可以为每个文件编号提取所有PIECE_WGT属性和元素
private IEnumerable<FILELOGElements> FileInfo(XElement doc, string FileNo)
{
IEnumerable <FILELOGElements> Info = from el in doc.Elements("FILE_NO")
where el.Attribute("ID").Value.ToUpper() == FileNo
select new FILELOGElements
{
FileNo = el.Attribute("ID").Value.ToUpper(),
TotPieces = Convert.ToDouble(el.Element("TOTAL_PIECES").Value),
TotWeight = Convert.ToDouble(el.Element("TOTAL_WEIGHT").Value),
PiecesUsed = Convert.ToDouble(el.Element("PIECES_USED").Value),
Pieces = el.Elements("PIECE_WGT").Attributes("CNT").Select(a => Convert.ToDouble(a.Value)).ToList(),
Weight = el.Elements("PIECE_WGT").Select(a => Convert.ToDouble(a.Value)).ToList()
};
return Info;
}
}
class FILELOGElements
{
public string FileNo { get; set; }
public double TotPieces { get; set; }
public double TotWeight { get; set; }
public double PiecesUsed { get; set; }
public List<double> Pieces { get; set; }
public List<double> Weight { get; set; }
}