且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用linq将xml数据加载到表中

更新时间:2023-10-31 16:07:40

{1 } \t {2},product.Name,product.Price,product.Category);
}
}
}
catch (Exception ex)
{

throw ex;
}
}
}
}< pre>
{1}\t{2}", product.Name, product.Price, product.Category); } } } catch (Exception ex) { throw ex; } } } }<pre>


您可以使用LINQ to XML库

...在任何地方,codeproject上都有大量的例子可以给你一个见解。



You could make use of the LINQ to XML library
...anywhere, there are tons of examples here on codeproject that should give you an insight.

XDocument doc = GetDocument();
// assuming this is the correct namespace
XNamespace s = "http://www.google.com/shopping/api/schemas/2010";
var query =
    from product in doc.Root.Elements("entry").Elements(s + "product")
    // declare some variables to make the query cleaner
    let inventory = product.Element(s + "inventories").Element(s + "inventory")
    let price = (decimal)inventory.Element(s + "price")
    let shipping = (decimal)inventory.Element(s + "price").Attribute("shipping")
    select new
    {
        Name = (string)product.Element(s + "author").Element(s + "name"),
        Condition = (string)product.Element(s + "condition"),
        Price = price,
        Shipping = shipping,
        TotalPrice = price + shipping,
        Availability = (string)inventory.Attribute("availability"),
    };

var dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Condition", typeof(string));
dt.Columns.Add("Price", typeof(decimal));
dt.Columns.Add("Shipping", typeof(decimal));
dt.Columns.Add("TotalPrice", typeof(decimal));
dt.Columns.Add("Availability", typeof(string));
foreach (var product in query)
{
    dt.Rows.Add(
        product.Name,
        product.Condition,
        product.Price,
        product.Shipping,
        product.TotalPrice,
        product.Availability
    );
}