public LastfmResponse<LastfmUserItem> Parse(XElement xmlResponse) { lfmNodeErrorParser.Parse(xmlResponse); var tracks = xmlResponse.DescendantsAndSelf(CollectionElementName); var tracksElement = tracks.First(); return CreateUserItem(tracksElement); }
/// <summary> /// 获取XElement文件树节点段XElement /// </summary> /// <param name="xml">XElement文件载体</param> /// <param name="mainnode">要查找的主节点</param> /// <param name="attribute">主节点条件属性名</param> /// <param name="value">主节点条件属性值</param> /// <returns>以该主节点为根的XElement</returns> public static XElement GetXElement(XElement XElement, string newroot, string attribute, string value) { if (XElement != null) { IEnumerable<XElement> xmlItems = XElement.DescendantsAndSelf(newroot); if (xmlItems != null) { foreach (var xmlItem in xmlItems) { XAttribute attrib = null; if (xmlItem != null) attrib = xmlItem.Attribute(attribute); if (null != attrib && attrib.Value == value) { return xmlItem; } } } return null; } else { DebugMod.LogError(new Exception(string.Format("GetXElement异常, 读取: {0}/{1}={2} 失败, xml节点名: {3}", newroot, attribute, value, GetXElementNodePath(XElement)))); return null; } }
public XElementContext(XElement root, XizzleConventions conventions = null) { Conventions = conventions ?? DefaultConventions; RootElement = root; _idDict = new Dictionary<string, XElement>(); _typeDict = new Dictionary<string, HashSet<XElement>>(); _attrDict = new Dictionary<string, HashSet<XElement>>(); foreach (var el in RootElement.DescendantsAndSelf()) { IEnumerable<XAttribute> nameAttributes = el.Attributes() .Where(a => a.Name.LocalName == Conventions.IdAttributeName()); foreach (XAttribute attr in nameAttributes) _idDict[attr.Value] = el; if (!_typeDict.ContainsKey(el.Name.LocalName)) _typeDict[el.Name.LocalName] = new HashSet<XElement>(); _typeDict[el.Name.LocalName].Add(el); foreach (XAttribute a in el.Attributes()) { if (!_attrDict.ContainsKey(a.Name.LocalName)) _attrDict[a.Name.LocalName] = new HashSet<XElement>(); _attrDict[a.Name.LocalName].Add(el); } } }
public static XElement GetMergeScript(string start, string dest) { if (string.IsNullOrWhiteSpace(start)) return new XElement("AML"); var startElem = XElement.Parse(start); var result = new XElement(startElem.Name); // Create deletes if (string.IsNullOrEmpty(dest)) { var itemTag = startElem.DescendantsAndSelf().First(e => e.Name.LocalName == "Item"); var items = itemTag.Parent.Elements("Item").Where(e => e.Attribute("action") != null && (e.Attribute("action").Value == "merge" || e.Attribute("action").Value == "add" || e.Attribute("action").Value == "create")); XElement newItem; foreach (var item in items) { newItem = new XElement(item.Name, item.Attributes().Where(IsAttributeToCopy)); newItem.SetAttributeValue("action", "delete"); } return result; } // Create merges/deletes as necessary var destElem = XElement.Parse(dest); GetMergeScript(startElem, destElem, result); foreach (var elem in result.DescendantsAndSelf()) elem.RemoveAnnotations<ElementKey>(); return result; }
internal static void ReplaceFormTagByDivTag(XElement document) { foreach (var form in document.DescendantsAndSelf(ns + "form")) { form.Name = ns + "div"; } }
protected virtual RssVersion GetVersion() { // Checking the version // Example: <rss version="2.0"> IEnumerable <XElement> rssXElement; IEnumerable <XAttribute> versionXAttribute; string rssVersionString; rssXElement = rssXml.DescendantsAndSelf((XName)"rss"); versionXAttribute = rssXElement.Attributes((XName)"version"); // need to check the behaviour of Current rssVersionString = versionXAttribute.GetEnumerator().Current.Value; switch (rssVersionString) { case "1.0": rssVersion = RssVersion.v10; break; case "2.0": rssVersion = RssVersion.v20; break; } }
public CProfile(XElement xml) { foreach (XElement item in xml.DescendantsAndSelf ("row")) { // ProfileItems.Add(CService.GetString(item, "profileItem"), CService.GetObject(item, "value", CService.GetString(item, "type"))); } }
private List<string> ReadReferencedAssemblyNames(XElement xml) { List<string> rawAssemblyNames = (from r in xml.DescendantsAndSelf(Ns + "Reference") where r.Parent.Name == Ns + "ItemGroup" select r.Attribute("Include").Value).ToList(); List<string> unQualifiedAssemblyNames = rawAssemblyNames.ConvertAll(UnQualify); return unQualifiedAssemblyNames; }
public LastfmResponse<LastfmLibraryItem> Parse(XElement xmlResponse) { lfmNodeErrorParser.Parse(xmlResponse); var collection = xmlResponse.DescendantsAndSelf(CollectionElementName); var collectionElement = collection.First(); return CreateLibraryItem(collectionElement); }
private static void RemoveDebugInfo(IScope scope, XElement result) { if (!scope.Get("debug_render", false)) { foreach (var element in result.DescendantsAndSelf()) { element.SetAttributeValue("_file", null); element.SetAttributeValue("_line", null); } } }
protected override string GetNzbInfoUrl(XElement item) { IEnumerable<XElement> matches = item.DescendantsAndSelf("link"); if (matches.Any()) { return matches.First().Value; } return String.Empty; }
public IEnumerable<XElement> ExtractElements(XElement ast) { foreach (var nameAndRules in FilterDictionary) { var elements = ast.DescendantsAndSelf(nameAndRules.Key); var rules = nameAndRules.Value; var results = elements.Where(e => rules.All(rule => rule.IsAcceptable(e))); foreach (var result in results) { yield return result; } } }
protected override long GetSize(XElement item) { IEnumerable<XElement> matches = item.DescendantsAndSelf("enclosure"); if (matches.Any()) { XElement enclosureElement = matches.First(); return Convert.ToInt64(enclosureElement.Attribute("length").Value); } return 0; }
public RssFile(string inputFileName) { this.fileName = inputFileName; rssXml = System.Xml.Linq.XElement.Load(fileName); rssXmlElements = rssXml.DescendantsAndSelf(); // Checking the version // Example: <rss version="2.0"> GetVersion(); }
private void BuildWiki(StringBuilder sb, XElement e){ haserrors = false; int nscnt = 1; var namespaces = new Dictionary<string, string>(); foreach (XElement element in e.DescendantsAndSelf()){ if (!string.IsNullOrWhiteSpace(element.Name.NamespaceName)){ if (element.Name.NamespaceName == "http://www.w3.org/2000/xmlns/") continue; if (!namespaces.ContainsKey(element.Name.NamespaceName)){ namespaces[element.Name.NamespaceName] = "ns" + nscnt++; } } foreach (XAttribute attr in element.Attributes()){ if (!string.IsNullOrWhiteSpace(attr.Name.NamespaceName)){ if (attr.Name.NamespaceName == "http://www.w3.org/2000/xmlns/") continue; if (!namespaces.ContainsKey(attr.Name.NamespaceName)){ namespaces[attr.Name.NamespaceName] = "ns" + nscnt++; } } } } sb.AppendLine("<div class='wk-x'>"); if (!_showroot){ if (namespaces.Count != 0){ sb.AppendLine( "<!-- документы XML полученные из BXL/B# выводятся (в WIKI) не от корня, справка по пространствам имен:"); sb.AppendLine("<br/>"); foreach (var ns in namespaces){ sb.AppendLine(ns.Value + " :: " + ns.Key); sb.AppendLine("<br/>"); } sb.AppendLine("-->"); sb.AppendLine("<br/>"); } } if (_showroot){ BuildWiki(sb, e, 0, namespaces); } else{ foreach (XElement element in e.Elements()){ BuildWiki(sb, element, 0, namespaces); } } sb.AppendLine("</div>"); if (haserrors){ sb.AppendLine("<div class='wk-x-error'>"); foreach (XElement element in e.Elements()){ if (element.Name.LocalName != "bx-error") continue; Append(sb, element.Value, "wk-x-error-" + element.Attr("level"), tagname: "div"); } sb.AppendLine("</div>"); } }
public static string File(string id, XElement xaml, string type = null, string path = null) { var e = xaml.DescendantsAndSelf(xic + id).FirstOrDefault(); if (e != null) { if (e.Attribute(xic+"ImageType") != null) type = (string)e.Attribute(xic+"ImageType"); if (e.Attribute(xic+"Cache") != null) path = (string)e.Attribute(xic+"Cache"); } path = path ?? Path; if (type == null) type = "png"; if (!path.EndsWith("/")) path += "/"; return path + id + "." + Hash.Compute(xaml).ToString() + "." + type; }
public static int AnalyzeFirstLineNumberOrDefault(XElement elem) { foreach (var e in elem.DescendantsAndSelf()) { if (IgnoredElements.Contains(e.Name())) { continue; } var attr = e.Attribute("startline"); if (attr != null) { return int.Parse(attr.Value); } } return 0; }
/// <summary> /// Creates definitions from this file unit /// </summary> /// <param name="fileUnit">The file unit.</param> /// <returns>an enumerable of definition objects to be inserted into the database</returns> public IEnumerable<Definition> GetDefinitionsFromFileUnit(XElement fileUnit) { if (fileUnit == null) throw new ArgumentNullException("fileUnit"); var fileName = fileUnit.Attribute("filename").Value; var definitions = from child in fileUnit.DescendantsAndSelf() where Definition.ValidNames.Contains(child.Name) let defs = Definition.CreateFromElement(child, fileName, this.Id) from def in defs select def; return definitions; }
public void FillContent(XElement contentControl, IContentItem item) { if (!(item is ImageContent)) { _processResult = ProcessResult.NotHandledResult; return; } var field = item as ImageContent; // If image bytes was not provided, then doing nothing if (field.Binary == null || field.Binary.Length == 0) { return; } // If there isn't a field with that name, add an error to the error string, // and continue with next field. if (contentControl == null) { _processResult.Errors.Add(String.Format("Field Content Control '{0}' not found.", field.Name)); return; } var blip = contentControl.DescendantsAndSelf(A.blip).First(); if (blip == null) { _processResult.Errors.Add(String.Format("Image to replace for '{0}' not found.", field.Name)); return; } // Creating a new image part var imagePart = _context.WordDocument.MainDocumentPart.AddImagePart(field.MIMEType); // Writing image bytes to it using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream())) { writer.Write(field.Binary); } // Setting reference for CC to newly uploaded image blip.Attribute(R.embed).Value = _context.WordDocument.MainDocumentPart.GetIdOfPart(imagePart); //var imageId = blip.Attribute(R.embed).Value; //var xmlPart = _context.WordDocument.MainDocumentPart.GetPartById(imageId); //if (xmlPart is ImagePart) //{ // ImagePart imagePart = xmlPart as ImagePart; // using (BinaryWriter writer = new BinaryWriter(imagePart.GetStream())) // { // writer.Write(field.Binary); // } //} }
static void SetDefaultNamespace(XElement element, XNamespace newXmlns) { var currentXmlns = element.GetDefaultNamespace(); if (currentXmlns == newXmlns) { return; } foreach (var descendant in element.DescendantsAndSelf() .Where(e => e.Name.Namespace == currentXmlns)) { descendant.Name = newXmlns.GetName(descendant.Name.LocalName); } }
internal static void ValidateIdentifiers(XElement xElement) { var duplicates = (from id in xElement.DescendantsAndSelf(Id) select id.Value).GroupBy(x => x).Where(y => y.Count() > 1).Select(z => new {z.Key, Count = z.Count()}).ToList(); if (duplicates.Any()) { var message = new StringBuilder(); foreach (var duplicate in duplicates) { if (message.Length > 0) message.Append("\n"); message.AppendFormat("{0} appeared {1} times", duplicate.Key, duplicate.Count); } throw new ArgumentException(string.Format("Duplicate identifiers found. Following is the list \n{0}", message)); } }
public void MoveNamespace() { var tree1 = new XElement( "Data", new XElement( "Child", "content", new XAttribute("MyAttr", "content"))); tree1.MoveToNamespace(NewNamespace); foreach (XElement node in tree1.DescendantsAndSelf()) { Check.That(node).IsInNamespace(NewNamespace.NamespaceName); } }
public void MoveNamespace() { var tree1 = new XElement( "Data", new XElement( "Child", "content", new XAttribute("MyAttr", "content"))); tree1.MoveToNamespace(newNamespace); foreach (XElement node in tree1.DescendantsAndSelf()) { node.ShouldBeInInNamespace(newNamespace.NamespaceName); } }
public static List<XElement> FindDifferentElements( XElement modified, List<DiffierentLine> diffLines) { var iLines = 0; var ret = new List<XElement>(); foreach (var elem in modified.DescendantsAndSelf()) { if (AnalyzeFirstLineNumberOrDefault(elem) == diffLines[iLines].LineNumber && AnalyzeLastLineNumberOrDefault(elem) == diffLines[iLines].LineNumber) { ret.Add(elem); iLines++; if (iLines == diffLines.Count) { break; } } } return ret; }
/// <summary> /// 获取XElement文件树节点段XElement /// </summary> /// <param name="XElement">XElement文件载体</param> /// <param name="newroot">要查找的独立节点</param> /// <returns>独立节点XElement</returns> public static XElement GetXElement(XElement XElement, string newroot) { if (XElement != null) { IEnumerable<XElement> xmlItems = XElement.DescendantsAndSelf(newroot); if (xmlItems == null) return null; foreach (var xmlItem in xmlItems) { return xmlItem; } return null; } return null; }
public static void CriteriaToWhereClause(XElement elem) { var item = elem.DescendantsAndSelf("Item").First(); if (item.Attribute("type") == null) return; var builder = new CriteriaBuilder() { Operator = "and", Type = "[" + item.Attribute("type").Value.Replace(' ', '_') + "]" }; ProcessCriteria(elem, builder); var where = item.Attribute("where"); var whereClause = builder.ToString(); if (where != null) whereClause += " and " + where.Value; item.SetAttributeValue("where", whereClause); }
public ProcessResult FillContent(XElement contentControl, IContentItem item) { var processResult = ProcessResult.NotHandledResult; if (!(item is ImageContent)) { processResult = ProcessResult.NotHandledResult; return processResult; } var field = item as ImageContent; // If there isn't a field with that name, add an error to the error string, // and continue with next field. if (contentControl == null) { processResult.AddError(new ContentControlNotFoundError(field)); return processResult; } var blip = contentControl.DescendantsAndSelf(A.blip).First(); if (blip == null) { processResult.AddError(new CustomContentItemError(field, "doesn't contain an image for replace")); return processResult; } var imageId = blip.Attribute(R.embed).Value; var imagePart = (ImagePart)_context.Document.GetPartById(imageId); if (imagePart != null) { _context.Document.RemovePartById(imageId); } var imagePartId = _context.Document.AddImagePart(field.Binary); blip.Attribute(R.embed).SetValue(imagePartId); processResult.AddItemToHandled(item); return processResult; }
/// <summary> /// Sets the default XML namespace of this System.Xml.Linq.XElement and all its descendants /// </summary> public static void SetDefaultNamespace(this XElement element, XNamespace newXmlns) { if (newXmlns == null) { return; } var currentXmlns = element.GetDefaultNamespace(); if (currentXmlns == newXmlns) { return; } foreach (var descendant in element.DescendantsAndSelf() .Where(e => e.Name.Namespace == currentXmlns)) //!important { descendant.Name = newXmlns.GetName(descendant.Name.LocalName); } }
/// <summary> /// Gets the XML node located at the specified line and position. /// </summary> /// <param name="rootElement">The root element.</param> /// <param name="lineNumber">One-based line number.</param> /// <param name="linePosition"> /// One-based line position. The line position of an XML element is equal to the position /// of the first character in its name, not the position of the opening angle bracket. /// E.g. the XML fragment "<element />" has line position 2. /// </param> /// <returns>The matching XML node or <c>null</c> if no match was found.</returns> public XElement GetElement(XElement rootElement, int lineNumber, int linePosition) { if(rootElement == null) { return null; } var elements = rootElement.DescendantsAndSelf(); var matchingElement = (from element in elements where IsCorrectLine(element, lineNumber) where IsCorrectPosition(element, linePosition) select element).LastOrDefault(); if(matchingElement != null) { return matchingElement; } var matchingAttribute = GetAttribute(elements, lineNumber, linePosition); return matchingAttribute == null ? null : matchingAttribute.Parent; }
static void rename(XElement root) { string newName; Dictionary<string, string> newProps; string newProp; foreach (var el in root.DescendantsAndSelf().ToArray()) { //rename enum values replaceValue(el); renameProps.TryGetValue(el.Name.LocalName, out newProps); if (renameEl.TryGetValue(el.Name.LocalName, out newName)) { renameCount++; //rename element el.Name = newName; } if (newProps != null) foreach (var att in el.Attributes().ToArray()) { if (newProps.TryGetValue(att.Name.LocalName, out newProp)) { renameCount++; //rename attr el.Add(new XAttribute(newProp, att.Value)); att.Remove(); } } } }
private static void strip_namespaces(SXL.XElement root) { foreach (var e in root.DescendantsAndSelf()) { if (e.Name.Namespace != SXL.XNamespace.None) { e.Name = SXL.XNamespace.None.GetName(e.Name.LocalName); } if ( e.Attributes().Any(a => a.IsNamespaceDeclaration || a.Name.Namespace != SXL.XNamespace.None)) { e.ReplaceAttributes( e.Attributes().Select( a => a.IsNamespaceDeclaration ? null : a.Name.Namespace != SXL.XNamespace.None ? new SXL.XAttribute( SXL.XNamespace.None.GetName(a.Name.LocalName), a.Value) : a)); } } }
public static Packet ConvertPacketFromXml(XElement xmlElement) { foreach (var el in xmlElement.DescendantsAndSelf()) { var xAttribute = el.Attribute("xmlns"); if (xAttribute != null) { XNamespace aw = xAttribute.Value; if (el.Name.Namespace != aw) el.Name = aw.GetName(el.Name.LocalName); } else { if (el.Parent != null) { el.Name = el.Parent.Name.Namespace.GetName(el.Name.LocalName); } } } return new Packet(xmlElement); }
public DagligPuddervarsel[] ProcessResponse(XElement forecastResponse) { var items = forecastResponse.DescendantsAndSelf("time"); var xElements = items as XElement[] ?? items.ToArray(); var powderForecastDays = new DagligPuddervarsel[xElements.Count()]; var i = 0; string temperature = string.Empty; foreach (var xElement in xElements) { var from = XmlHelper.GetAttributeValue("from", xElement); var to = XmlHelper.GetAttributeValue("to", xElement); var precipitation = XmlHelper.GetElementValue("location", "precipitation", "value", xElement); var temp = XmlHelper.GetElementValue("location", "temperature", "value", xElement); if (!string.IsNullOrEmpty(temp)) temperature = temp; if (!string.IsNullOrEmpty(precipitation)) { const string format = "yyyy-MM-ddTHH:mm:ssZ"; var powderForecast = new DagligPuddervarsel(); var ciNo = new CultureInfo("nb-NO"); powderForecast.Precipitation = Convert.ToDecimal((string) precipitation.Replace('.', ','), ciNo); powderForecast.From = DateTime.ParseExact(from, format, ciNo); powderForecast.To = DateTime.ParseExact(to, format, ciNo); if (!string.IsNullOrEmpty(temperature)) powderForecast.Temperature = Math.Round(Convert.ToDecimal((string)temperature.Replace('.', ','), ciNo),1); powderForecastDays[i] = powderForecast; i++; } } return powderForecastDays; }
public IActionResult atom() { var xml = new XElement("feed", new XElement("title", Settings.Title), new XElement("subtitle", Settings.Description), new XElement("link", new XAttribute("href", Settings.Domain)), new XElement("updated", livePosts.First().Timestamp.ToString("s") + "-05:00"), new XElement("id", Settings.Domain), livePosts .Select(p => new XElement("entry", new XElement("author", new XElement("name", Settings.Title)), new XElement("title", p.Title), new XElement("summary", p.Description), new XElement("link", new XAttribute("href", p.FullURL)), new XElement("updated", p.Timestamp.ToString("s") + "-05:00"), new XElement("id", p.FullURL) ) ) ); foreach (var element in xml.DescendantsAndSelf()) element.Name = XName.Get(element.Name.LocalName, "http://www.w3.org/2005/Atom"); return new ContentResult { Content = xml.ToString(), ContentType = "application/atom+xml" }; }
public void SetupEnumerator() { XElement doc = XElement.Parse("<a><sub1/><sub1/><sub2/><sub1/><sub2/><sub1/><sub2/><sub1/><sub2/><sub1/><sub2/><sub2/></a>"); _list = doc.DescendantsAndSelf(); }