如何将每个属性作为XElement?
我基本上试图将IEnumerable对象转换为Web服务中的XML。
这是我尝试转换为XML的代码。
CollectionChanged
修改
类别类定义(使用EntityFramework 6 Code First)
observableCollection.CollectionChanged += (ss, ee) =>
{
if(ee.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
SomeType newItem = ee.NewItems[0] as SomeType;
someObject.AddItem(newItem);
}
};
修改2
折扣类别定义
DataGrid
Product_Category_Mapping类定义
using (var db = new nopMass())
{
var cats = db.Categories
.Where(x => x.Deleted == false
&& x.Published == true)
.OrderBy(x => x.DisplayOrder)
.AsEnumerable()
.Select(cat => new Category
{
Id = cat.Id,
Name = cat.Name,
Description = cat.Description,
MetaKeywords = cat.MetaKeywords,
MetaDescription = cat.MetaDescription,
MetaTitle = cat.MetaTitle,
PictureId = cat.PictureId,
DisplayOrder = cat.DisplayOrder,
CreatedOnUtc = cat.CreatedOnUtc,
Product_Category_Mapping = cat.Product_Category_Mapping,
ParentCategoryId = cat.ParentCategoryId,
})
.ToArray();
XElement Configuration = new XElement("Collection",
cats
.ToList()
.Select(c => new XElement("Element", c)));
return Configuration.ToString();
}
答案 0 :(得分:1)
使用节点的OuterXml属性。它会准确地返回你想要的东西。
return Configuration.OuterXml;
答案 1 :(得分:0)
因此你实际上需要xml字符串,最简单的方法就是简单的xml序列化。例如。如果您有以下类别:
var cats = new List<Category> {
new Category { Id = 1, Name = "Auto", Description = "blah-blah-blah" },
new Category { Id = 2, Name = "Moto", Description = "bikes!" }
};
序列化将类似于
var serializer = new XmlSerializer(typeof(List<Category>),
new XmlRootAttribute("Categories"));
using (var writer = new StringWriter())
{
serializer.Serialize(writer, cats);
return writer.ToString();
}
输出:
<?xml version="1.0" encoding="utf-16"?>
<Categories xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Category>
<Id>1</Id>
<Name>Auto</Name>
<Description>blah-blah-blah</Description>
</Category>
<Category>
<Id>2</Id>
<Name>Moto</Name>
<Description>bikes!</Description>
</Category>
</Categories>
答案 2 :(得分:0)
这是我能想到的最佳解决方案。它有效,所以接受它作为我的答案。
$doc = new DOMDocument('1.0', 'UTF-8');
$internalErrors = libxml_use_internal_errors(true);
if ($doc->loadHTMLfile($url)) {
libxml_use_internal_errors($internalErrors);
$xpath = new DOMXpath($doc);
$namepath = '//*[@id="mod-product-detail-1"]/div/div[1]/div/div[2]/h1';
$pricepath = '//*[@id="mod-product-detail-1"]/div/div[1]/div/div[2]/div[3]/div[1]/span/span[2]';
//get name
$elements = $xpath->query($namepath);
if (!is_null($elements) && isset($elements[0]->nodeValue)) {
$data['name'] = $elements[0]->nodeValue;
} else {
$data['name'] = '';
}
//get price
$price = $xpath->query($pricepath);
if (!is_null($price) && isset($price[0]->nodeValue)) {
$data['price'] = filter_var($price[0]->nodeValue, FILTER_SANITIZE_NUMBER_INT);
} else {
$data['price'] = '';
}
}