I'm trying to follow Microsoft 's guide on XML serialization, but I'm having problems!
This is the XML file used as input:
<?xml version="1.0" encoding="utf-8"?>
<Books xmlns:books="http://www.cpandl.com" xmlns:money="http://www.cohowinery.com">
<money:Book>
<books:TITLE>A Book Title</books:TITLE>
<money:PRICE books:currency="US Dollar">
<money:price>9.95</money:price>
</money:PRICE>
</money:Book>
</Books>
This is the class for binding XML:
public class OrderedItem
{
[XmlElement(Namespace = "http://www.cpandl.com")]
public string ItemName;
[XmlElement(Namespace = "http://www.cpandl.com")]
public string Description;
[XmlElement(Namespace = "http://www.cohowinery.com")]
public decimal UnitPrice;
[XmlElement(Namespace = "http://www.cpandl.com")]
public int Quantity;
[XmlElement(Namespace = "http://www.cohowinery.com")]
public decimal LineTotal;
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}
This function reads the XML into the "OrderedItem" class:
Console.WriteLine("Reading with Stream");
var serializer = new XmlSerializer(typeof(OrderedItem));
Stream reader = new FileStream(filename, FileMode.Open);
var i = (OrderedItem)serializer.Deserialize(reader);
Console.SetOut(new StreamWriter("a_output.xml"));
serializer.Serialize(Console.Out, i);
This is the XML after reading and rewriting:
<?xml version="1.0" encoding="utf-8"?>
<OrderedItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ItemName xmlns="http://www.cpandl.com">Widget</ItemName>
<Description xmlns="http://www.cpandl.com">Regular Widget</Description>
<UnitPrice xmlns="http://www.cohowinery.com">2.3</UnitPrice>
<Quantity xmlns="http://www.cpandl.com">10</Quantity>
<LineTotal xmlns="http://www.cohowinery.com">23</LineTotal>
</OrderedItem>
As you can see, the namespace is expanded. How to write output to get the same XML with namespace label, not uri?
source
share