Skip to content

Commit

Permalink
Use XDocument instead of XmlDocument
Browse files Browse the repository at this point in the history
  • Loading branch information
ManniManfred committed Aug 31, 2014
1 parent 59283f0 commit 21f620d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
<Reference Include="System.Management" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\GlobalAssemblyInfo.cs">
Expand Down
57 changes: 37 additions & 20 deletions Source/MSBuild.Community.Tasks/XmlUpdate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,11 @@ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Linq;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using System.Xml.XPath;
using System.Xml.Linq;



Expand Down Expand Up @@ -152,35 +154,50 @@ public override bool Execute()
try
{
Log.LogMessage(Properties.Resources.XmlUpdateDocument, _xmlFileName);

XmlDocument document = new XmlDocument();
document.Load(_xmlFileName);

XPathNavigator navigator = document.CreateNavigator();
XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);

XDocument xdoc = XDocument.Load(_xmlFileName);
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());

if (!string.IsNullOrEmpty(_prefix) && !string.IsNullOrEmpty(_namespace))
{
manager.AddNamespace(_prefix, _namespace);
}

XPathExpression expression = XPathExpression.Compile(_xpath, manager);
XPathNodeIterator nodes = navigator.Select(expression);

Log.LogMessage(Properties.Resources.XmlUpdateNodes, nodes.Count);

while (nodes.MoveNext())
if (_delete)
nodes.Current.DeleteSelf();
else
nodes.Current.SetValue(_value ?? string.Empty);

var items = xdoc.XPathEvaluate(_xpath, manager) as IEnumerable<object>;

Log.LogMessage(Properties.Resources.XmlUpdateNodes, items.Count());

using (XmlTextWriter writer = new XmlTextWriter(_xmlFileName, Encoding.UTF8))
foreach (var item in items.ToArray())
{
writer.Formatting = Formatting.Indented;
document.Save(writer);
writer.Close();
var attr = item as XAttribute;
if (attr != null)
{
if (_delete)
{
attr.Remove();
}
else
{
attr.SetValue(_value);
}
}

var ele = item as XElement;
if (ele != null)
{
if (_delete)
{
ele.Remove();
}
else
{
ele.SetValue(_value);
}
}
}

xdoc.Save(_xmlFileName);
}
catch (Exception ex)
{
Expand Down

0 comments on commit 21f620d

Please sign in to comment.