我是Linq to xml的新手。我的xml字符串如下:
<root>
<add>
<item id="jqg1" moduleid="F0736590-84A2-4795-BC5D-0056606F2446" view="1" add="1" edit="0" del="0" />
</add>
<update>
<item id="jqg3" moduleid="3C414435-DBBE-4B4E-A790-14B67F050EB0" view="1" add="1" edit="1" del="0" />
</update>
</root>
从jquery发送到放置在texbox内的C#(文本框Visible = false)。
注意:元素可以在每个元素中多个。
在C#上读取xml字符串的代码点击eevnt。
string paramXML = txtXmlStr.Text;
var l_sID = "";
var l_sMODID = "";
var l_sVIEW = "";
var l_sADD = "";
var l_sEDIT = "";
var l_sDEL = "";
if (!string.Empty.Equals(paramXML))
{
var l_oXDoc = XDocument.Parse(paramXML.ToLower());
==> var addParams = from addParam in l_oXDoc.Element("add").Elements("item")
select new
{
l_sID = addParam.Attribute("id").Value,
l_sMODID = addParam.Attribute("moduleId").Value,
l_sVIEW = addParam.Attribute("view").Value,
l_sADD = addParam.Attribute("add").Value,
l_sEDIT = addParam.Attribute("edit").Value,
l_sDEL = addParam.Attribute("del").Value,
};
foreach (var oParam in addParams)
{
string id = oParam.l_sID.Trim();
string modid = oParam.l_sMODID.Trim();
string view = oParam.l_sMODID.Trim();
string add = oParam.l_sMODID.Trim();
string edit = oParam.l_sMODID.Trim();
string del = oParam.l_sMODID.Trim();
}
我在代码中指定的箭头上面出现错误。我该如何解决这个错误?
* 注意: *我的目标是将<Add>
元素的<item>
元素数据读入一个变量,我也想对<update>
元素执行相同操作。这是可能的......每个人的建议,想法和代码都是受欢迎的....
答案 0 :(得分:1)
属性/元素名称区分大小写。
替换
l_sMODID = addParam.Attribute("moduleId").Value,
使用
l_sMODID = addParam.Attribute("moduleid").Value,
这是因为输入XML中的属性是moduleid="F0736590-84A2-4795-BC5D-0056606F2446"
,而不是moduleId
。
工作代码:
var doc = XDocument.Load("Input.txt");
Func<XElement, IEnumerable<Item>> query = e => e.Elements("item")
.Select(x => new Item
{
Id = (string)x.Attribute("id"),
ModuleId = (string)x.Attribute("moduleid"),
View = (bool)x.Attribute("view"),
Add = (bool)x.Attribute("add"),
Edit = (bool)x.Attribute("edit"),
Delete = (bool)x.Attribute("del")
});
var addItems = query(doc.Root.Element("add")).ToList();
var updateItems = query(doc.Root.Element("update")).ToList();
Item
班级声明:
public class Item
{
public string Id { get; set; }
public string ModuleId { get; set; }
public bool View { get; set; }
public bool Add { get; set; }
public bool Edit { get; set; }
public bool Delete { get; set; }
}
答案 1 :(得分:1)
您需要先获取根元素。变化:
var addParams = from addParam in l_oXDoc.Element("add").Elements("item")
要
var addParams = from addParam in
l_oXDoc.Descendants("root").First().Element("add").Elements("item")