What is a good way to modify XML files in C# using Saxon library?
Added by Funkmaster roch about 7 years ago
I have following scenario:
The user can create an XPath expression and start a query. Then the user can decide what should happen which the query result.
The options should be: delete, replace and add
E.g. The Xml File:
Gambardella, Matthew <title>XML Developer's Guide</title> Computer 44.95 2000-10-01 An in-depth look at creating applications with XML.XPath: catalog/book/genre --> result is "Computer"
User selects "delete" --> XPath result should be removed from Xml file and XML file should look like this:
Gambardella, Matthew <title>XML Developer's Guide</title> 44.95 2000-10-01 An in-depth look at creating applications with XML.My code for the XPath query looks like this:
static XdmValue XPathQuery(string xPathExpression, XdmNode xdmNode)
{
// Enable caching, so each expression is only compiled once
xPathCompiler.Caching = true;
XdmValue results = null;
try
{
// Compile and evaluate an XPath expression
results = xPathCompiler.Evaluate(xPathExpression, xdmNode);
}
catch (StaticError)
{
log.Info("Invalid XPath. Wrong syntax or semantic! " + xPathExpression);
}
catch (DynamicError)
{
log.Info("Error during evaluation of the XPath expression." + xPathExpression);
}
catch (Exception ex)
{
log.Info("Error at Evaluate the XPathQuery", ex);
}
log.Debug("Verification result is: " + results.Count);
foreach (var result in results)
{
log.Debug("Verification value is: " + "\"" + result.ToString() + "\"");
}
return results;
}
Replies (2)
RE: What is a good way to modify XML files in C# using Saxon library? - Added by Michael Kay about 7 years ago
I'd be inclined to use a mutable tree model here -- probably the Microsoft DOM, because the only alternative is the Saxon LinkedTree model, and that's not primarily designed for in-situ update. If the tree is a DOM, then you can get from the XdmNode objects to the underlying DOM Nodes, and use DOM operations to modify the tree.
Start with DocumentBuilder.wrap(XmlDocument) to build the input tree.
To get from a returned XdmNode to the underlying DOM Node, call XdmNode.Implementation to get a NodeInfo, cast this to class net.sf.saxon.dotnet.DotNetNodeWrapper, and call its getUnderlyingNode() method.
RE: What is a good way to modify XML files in C# using Saxon library? - Added by Funkmaster roch almost 7 years ago
Thanks Michael works perfect for me:
Here is my solution:
public XmlNode ConvertXdmNodeToXmlNode(XdmNode xdmNode)
{
// XdmNode which stores the XPath result
NodeInfo nodeInfo = xdmNode.Implementation;
DotNetNodeWrapper dotNetNodeWrapper = (DotNetNodeWrapper)nodeInfo;
var nodeType = dotNetNodeWrapper.getUnderlyingNode();
// cast from Object to XmlNode
XmlNode xmlNode = (XmlNode)nodeType;
return xmlNode;
}
Please register to reply