Reputation: 38109
Background: I am loading a class from a file through XamlReader.Load(), working with it and then saving it back to a file through XamlWriter.Save(). The original file has no null properties, but the resulting saved file has all properties whether or not they are null, and it bloats the file. So I would like to remove them before actually saving to disk.
I have the following xml fragment as a string. I need to remove all properties which have "{assembly:Null}" as the value.
<ElementMap ElementType="SegmentData"
Key="{assembly:Null}"
EntityPropertyMapping="SenderCode"
Name="Application Sender's Code"
ElementCode="GS02"
EdiDataType="AN"
EntityDataType="String"
MinLength="2"
MaxLength="15"
Position="0"
ElementIndex="2"
ValidateData="False"
Parent="{assembly:Null}"
IsRequired="True"
Note="{assembly:Null}"
Default="{assembly:Null}"
Example="{assembly:Null}"
ExcludeFromStringOutput="False" />
The end result would be:
<ElementMap
ElementType="SegmentData"
EntityPropertyMapping="SenderCode"
Name="Application Sender's Code"
ElementCode="GS02"
EdiDataType="AN"
EntityDataType="String"
MinLength="2"
MaxLength="15"
Position="0"
ElementIndex="2"
ValidateData="False"
IsRequired="True"
ExcludeFromStringOutput="False" />
So how can this be achieved?
Upvotes: 0
Views: 248
Reputation: 236318
You can use LINQ to XML:
var elementMap = XElement.Load(path_to_xml); // or XElement.Parse(xml_string)
elementMap.Attributes().Where(a => (string)a == "{assembly:Null}").Remove();
elementMap.Save(path_to_xml);
Extensions.Remove() method removes every matched attribute from parent node.
Upvotes: 3
Reputation: 22814
XElement element = //get the XElement
element = new XElement(element.Name,
element.Attributes.Where(a => (string)a != "{assembly:Null}")
.Concat(element.Elements()).ToArray());
Upvotes: 1