/// <summary> /// Gets a XmlReaderSettings from a XmlPeekSettings /// </summary> /// <returns>The xml reader settings.</returns> /// <param name="settings">Additional settings to tweak Xml Peek behavior.</param> private static XmlReaderSettings GetXmlReaderSettings(XmlPeekSettings settings) { var xmlReaderSettings = new XmlReaderSettings(); xmlReaderSettings.DtdProcessing = (DtdProcessing)settings.DtdProcessing; return(xmlReaderSettings); }
/// <summary> /// Gets the value of a target node. /// </summary> /// <returns>The value found at the given XPath query (or the first, if multiple eligible nodes are found).</returns> /// <param name="source">The source xml to transform.</param> /// <param name="xpath">The xpath of the nodes to set.</param> /// <param name="settings">Additional settings to tweak Xml Peek behavior.</param> private static string XmlPeek(XmlReader source, string xpath, XmlPeekSettings settings) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (string.IsNullOrWhiteSpace(xpath)) { throw new ArgumentNullException(nameof(xpath)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var document = new XmlDocument(); document.PreserveWhitespace = settings.PreserveWhitespace; document.Load(source); var navigator = document.CreateNavigator(); var namespaceManager = new XmlNamespaceManager(navigator.NameTable); foreach (var xmlNamespace in settings.Namespaces) { namespaceManager.AddNamespace(xmlNamespace.Key /* Prefix */, xmlNamespace.Value /* URI */); } var node = navigator.SelectSingleNode(xpath, namespaceManager); return(node?.Value); }
public static string XmlPeek(this ICakeContext context, FilePath filePath, string xpath, XmlPeekSettings settings) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var file = context.FileSystem.GetFile(filePath); if (!file.Exists) { throw new FileNotFoundException("Source File not found.", file.Path.FullPath); } using (var fileStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None)) using (var xmlReader = XmlReader.Create(fileStream, GetXmlReaderSettings(settings))) { var xmlValue = XmlPeek(xmlReader, xpath, settings); if (xmlValue == null && !settings.SuppressWarning) { context.Log.Warning("Warning: Failed to find node matching the XPath '{0}'", xpath); } return(xmlValue); } }