DataContractSerializer之后无法访问Element [英] Can't access Element after DataContractSerializer
问题描述
我有一个简单的对象,正在尝试使用DataContractSerializer进行序列化.
I have a simple object I'm trying to serialize using DataContractSerializer.
在单元测试中,我试图验证xml是否包含product/sku节点的正确值.
In my unit test, I'm trying to verify the xml contains the right value for the product/sku node.
我的产品类别:
[DataContract(Namespace = "http://foo.com/catalogue/")
partial class Product
{
[DataMember(Name = "sku")]
public virtual string ProductSKU
{
get { return _productSKU; }
set
{
OnProductSKUChanging();
_productSKU = value;
OnProductSKUChanged();
}
}
}
这是我正在测试的方法:
Here's the method I'm testing:
public XDocument GetProductXML(Product product)
{
var serializer = new DataContractSerializer(typeof(Product));
var document = new XDocument();
using (var writer = document.CreateWriter())
{
serializer.WriteObject(writer, product);
writer.Close();
}
return document;
}
这是我的单元测试:
[Test]
public void Can_get_product_xml()
{
// Arrange
var product = new Product {Id = 1, Name = "Foo Balls", ProductSKU = "Foo123"};
var repository = new CatalogueRepository();
var expectedProductSKU = "Foo123";
// Act
var xml = repository.GetProductXML(product);
var actualProductSKU = xml.Element("product").Element("sku").Value;
// Assert
Assert.AreEqual(expectedProductSKU, actualProductSKU);
}
问题是,即使我设置断点时var xml包含以下内容,当我尝试访问xml元素时也会得到一个Null引用:
The problem is that I get a Null reference when I try and access the xml elements, even though when I set a break point the var xml contains:
<product xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://foo.com catalogue/">
<sku>Foo123</sku>
</product>
有什么想法为什么不起作用?在将序列化的流添加到XDocument之前,我需要解析它吗?
Any ideas why this is not working? Do I need to parse the serialized stream before adding it to the XDocument?
推荐答案
我认为问题在于您的XML文档具有XML名称空间xmlns="http://foo.com catalogue/"
,但是当您选择使用Linq-to-XML时,您会发现永远不要以任何方式,形状或形式使用该名称空间.
I would think the problem lies in the fact your XML document has a XML namespace xmlns="http://foo.com catalogue/"
, but when you select using Linq-to-XML, you're never using that namespace in any way, shape or form.
此外,<product>
标记是您的XML根标记-您不能将其作为元素引用.
Also, the <product>
tag is your XML root tag - you cannot reference that as an element.
尝试这样的事情:
XNamespace ns = "http://foo.com/catalogue/";
var root = xml.Root;
var sku = root.Element(xns + "sku").Value;
如果要确定,请首先将.Element()
分配给变量,然后检查!= null
If you want to be sure, first assign .Element()
to a variable and check for != null
var sku = root.Element(xns + "sku");
if(sku != null)
{
var skuValue = first.Value;
}
希望能有所帮助!
这篇关于DataContractSerializer之后无法访问Element的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!