本文整理汇总了C#中System.Xml.Linq.XDocument.DescendantNodes方法的典型用法代码示例。如果您正苦于以下问题:C# XDocument.DescendantNodes方法的具体用法?C# XDocument.DescendantNodes怎么用?C# XDocument.DescendantNodes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Xml.Linq.XDocument
的用法示例。
在下文中一共展示了XDocument.DescendantNodes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: get_report_list
public void get_report_list()
{
var username = "";
var password = "";
var ub = new UriBuilder("https", "reports.office365.com");
ub.Path = "ecp/reportingwebservice/reporting.svc";
var fullRestURL = Uri.EscapeUriString(ub.Uri.ToString());
var request = (HttpWebRequest)HttpWebRequest.Create(fullRestURL);
request.Credentials = new NetworkCredential(username, password);
try
{
var response = (HttpWebResponse)request.GetResponse();
var encode = System.Text.Encoding.GetEncoding("utf-8");
var readStream = new StreamReader(response.GetResponseStream(), encode);
var doc = new XDocument();
doc = XDocument.Load(response.GetResponseStream());
var nodes = doc.DescendantNodes().Where(x => x.NodeType == XmlNodeType.Text).ToList();
var node_str = string.Join(",", nodes);
doc.Save(@"C:\Office365\Reports\ReportList.xml");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
示例2: Wrap
/// <summary>
/// Wrap an existing <see cref="XDocument"/> as an <see cref="XdmNode"/>. This is the <see cref="XDocument"/>
/// equivalent of <see cref="DocumentBuilder.Wrap(XmlDocument)"/>.
/// </summary>
/// <remarks>
/// PoC:
///
/// Creates wrapper objects for all nodes in the document graph and stores them using
/// <see cref="XObject.AddAnnotation(object)"/>. Will throw if any node has already been wrapped.
///
/// Idealy this would be an extension to <see cref="DocumentBuilder"/>, but DocumentBuilder does not expose
/// its Configuration object publically.
/// </remarks>
public static XdmNode Wrap(this Processor processor, XDocument doc)
{
if (doc.Annotation<XObjectWrapper>() != null)
throw new InvalidOperationException("XDocument is already annotated with a wrapper.");
var docWrapper = (XDocumentWrapper)XObjectWrapper.MakeWrapper(doc);
docWrapper.setConfiguration(processor.Implementation);
doc.AddAnnotation(docWrapper);
foreach (var node in doc.DescendantNodes())
{
if (node.Annotation<XObjectWrapper>() != null)
throw new InvalidOperationException(string.Format("{0} is already annotated with a wrapper.", node.GetType().Name));
node.AddAnnotation(XObjectWrapper.MakeWrapper(node));
if (node.NodeType == XmlNodeType.Element)
{
foreach (var attr in ((XElement)node).Attributes())
{
if (attr.Annotation<XObjectWrapper>() != null)
throw new InvalidOperationException("Attribute is already annotated with a wrapper.");
attr.AddAnnotation(XObjectWrapper.MakeWrapper(attr));
}
}
}
return (XdmNode)XdmValue.Wrap(docWrapper);
}
示例3: RemoveComments
private void RemoveComments(XDocument document)
{
var comments = document.DescendantNodes().OfType<XComment>().ToArray();
foreach(var comment in comments)
{
comment.Remove();
}
}
示例4: Modify
public XDocument Modify(XDocument document)
{
var textNodes = document.DescendantNodes()
.OfType<XText>()
.Where(ShouldNormalize);
foreach (var textNode in textNodes)
{
textNode.Value = NormalizeWhitespace(textNode.Value);
}
return document;
}
示例5: ForceEmptyTagsWithNewlines
static void ForceEmptyTagsWithNewlines(XDocument document)
{
// this is to force compatibility with previous implementation,
// in particular, to support nested objects with null properties in them.
foreach (var childElement in
from x in document.DescendantNodes().OfType<XElement>()
where x.IsEmpty && !x.HasAttributes
select x)
{
childElement.Value = "\n";
}
}
示例6: FormatCodeSamples
private static XDocument FormatCodeSamples(XDocument doc, IEnumerable<IParser> parsers)
{
var xElements = doc.DescendantNodes().OfType<XElement>().ToList();
var codeSamples = xElements.Where(
node =>
node!=null
&& node.Attributes().Any(a => a.Name == "class" && a.Value == "csharpcode"));
foreach (var codeSample in codeSamples)
{
var encodedCSharp = codeSample.AsText();
var code = System.Net.WebUtility.HtmlDecode(encodedCSharp);
var formattedCode = Format(code, parsers);
var newContent = formattedCode.ParseXml();
codeSample.ReplaceWith(newContent);
}
return doc;
}
示例7: ShowAllComments
private static void ShowAllComments(XDocument doc)
{
Console.WriteLine("Comments:");
foreach (var item in doc.DescendantNodes().OfType<XComment>())
{
Console.WriteLine(item.ToString());
}
Console.WriteLine("End of Comments");
}
示例8: PrepareDocument
internal void PrepareDocument(XDocument document)
{
/* Remove all HTML comments (including conditional comments). */
document
.DescendantNodes()
.Where(node => node.NodeType == XmlNodeType.Comment)
.Remove();
/* In some cases a body element can't be found (if the HTML is totally hosed for example),
* so we create a new body element and append it to the document. */
XElement documentBody = GetOrCreateBody(document);
XElement rootElement = document.Root;
// TODO: handle HTML frames
var elementsToRemove = new List<XElement>();
/* Remove all scripts that are not readability. */
elementsToRemove.Clear();
rootElement.GetElementsByTagName("script")
.ForEach(scriptElement =>
{
string scriptSrc = scriptElement.GetAttributeValue("src", null);
if (string.IsNullOrEmpty(scriptSrc) || scriptSrc.LastIndexOf("readability") == -1)
{
elementsToRemove.Add(scriptElement);
}
});
RemoveElements(elementsToRemove);
/* Remove all noscript tags. */
elementsToRemove.Clear();
elementsToRemove.AddRange(rootElement.GetElementsByTagName("noscript"));
RemoveElements(elementsToRemove);
/* Remove all external stylesheets. */
elementsToRemove.Clear();
elementsToRemove.AddRange(
rootElement.GetElementsByTagName("link")
.Where(element => element.GetAttributeValue("rel", "").Trim().ToLower() == "stylesheet"
&& element.GetAttributeValue("href", "").LastIndexOf("readability") == -1));
RemoveElements(elementsToRemove);
/* Remove all style tags. */
elementsToRemove.Clear();
elementsToRemove.AddRange(rootElement.GetElementsByTagName("style"));
RemoveElements(elementsToRemove);
/* Remove all nav tags. */
elementsToRemove.Clear();
elementsToRemove.AddRange(rootElement.GetElementsByTagName("nav"));
RemoveElements(elementsToRemove);
/* Remove all anchors. */
elementsToRemove.Clear();
IEnumerable<XElement> anchorElements =
rootElement.GetElementsByTagName("a")
.Where(aElement => aElement.Attribute("name") != null && aElement.Attribute("href") == null);
elementsToRemove.AddRange(anchorElements);
RemoveElements(elementsToRemove);
/* Turn all double br's into p's and all font's into span's. */
// TODO: optimize?
string bodyInnerHtml = documentBody.GetInnerHtml();
bodyInnerHtml = _ReplaceDoubleBrsRegex.Replace(bodyInnerHtml, "</p><p>");
bodyInnerHtml = _ReplaceFontsRegex.Replace(bodyInnerHtml, "<$1span>");
documentBody.SetInnerHtml(bodyInnerHtml);
}
示例9: SubstitutePlaceHolders
internal void SubstitutePlaceHolders(XDocument doc, DistributedConfigurationSubstitutions configurationSubstitutions)
{
var descendantComments = doc.DescendantNodes().OfType<XComment>();
var comments = (from comment in descendantComments
let match = TypeIdentifier.Match(comment.Value)
where match.Success
select new { XComment = comment, Match = match }).ToList();
foreach (var comment in comments)
{
if (!comment.Match.Groups["selector"].Value.Equals("Replace"))
continue;
var parameters = new JavaScriptSerializer().DeserializeObject(comment.Match.Groups["object"].Value) as Dictionary<string, object>;
var xPath = parameters["XPath"] as string;
var value = parameters["Value"] as string;
var node = (comment.XComment.XPathEvaluate(xPath) as IEnumerable<object>).FirstOrDefault();
if (node is XElement)
((XElement)node).SetValue(value);
else if (node is XAttribute)
((XAttribute)node).SetValue(value);
comment.XComment.Remove();
}
var xmlAsString = doc.ToString(); // not efficient but clear and ok for usually small configs
xmlAsString = Variable.Replace(xmlAsString, match =>
{
var variableName = match.Groups["varName"].Value;
var variable = configurationSubstitutions.Variables
.FirstOrDefault(v => v.Name.Equals(variableName));
if (variable == null)
return match.Value;
return variable.Value;
});
xmlAsString = Escaping.Replace(xmlAsString, string.Empty);
var doc2 = XDocument.Parse(xmlAsString);
doc.ReplaceNodes(doc2.Nodes());
}
示例10: ShuffleXmlElementsValues
/// <summary>
/// Shuffle elements values of a XML document.
/// </summary>
/// <param name="xmlDocument">A XElement object for a shuffle.</param>
/// <param name="shuffleOnlyVowels">Specifies when only vowels shuffle is needed.</param>
/// <param name="separators">User defined words separators in xml elements values.</param>
public static void ShuffleXmlElementsValues(
XDocument xmlDocument,
Boolean shuffleOnlyVowels,
params Char[] separators
)
{
var textNodes = from node in xmlDocument.DescendantNodes()
where node is XText
select (XText)node;
foreach (var textNode in textNodes)
{
string tempValue = textNode.Value;
tempValue = ShuffleStatement(tempValue, shuffleOnlyVowels, separators);
textNode.Value = tempValue;
}
}
示例11: CreateDocument
/// <summary>
/// Creates the document.
/// </summary>
/// <param name="mergeTemplate">The merge template.</param>
/// <param name="mergeObjectList">The merge object list.</param>
/// <param name="globalMergeFields">The global merge fields.</param>
/// <returns></returns>
public override BinaryFile CreateDocument( MergeTemplate mergeTemplate, List<object> mergeObjectList, Dictionary<string, object> globalMergeFields )
{
this.Exceptions = new List<Exception>();
BinaryFile outputBinaryFile = null;
var rockContext = new RockContext();
var binaryFileService = new BinaryFileService( rockContext );
var templateBinaryFile = binaryFileService.Get( mergeTemplate.TemplateBinaryFileId );
if ( templateBinaryFile == null )
{
return null;
}
// Start by creating a new document with the contents of the Template (so that Styles, etc get included)
XDocument sourceTemplateDocX;
using ( MemoryStream outputDocStream = new MemoryStream() )
{
templateBinaryFile.ContentStream.CopyTo( outputDocStream );
outputDocStream.Seek( 0, SeekOrigin.Begin );
// now that we have the outputdoc started, simplify the sourceTemplate
var sourceTemplateStream = templateBinaryFile.ContentStream;
var simplifiedDoc = WordprocessingDocument.Open( sourceTemplateStream, true );
MarkupSimplifier.SimplifyMarkup( simplifiedDoc, this.simplifyMarkupSettingsAll );
//// simplify any nodes that have Lava in it that might not have been caught by the MarkupSimplifier
//// MarkupSimplifier only merges superfluous runs that are children of a paragraph
sourceTemplateDocX = simplifiedDoc.MainDocumentPart.GetXDocument();
OpenXmlRegex.Match(
sourceTemplateDocX.Elements(),
this.lavaRegEx,
( x, m ) =>
{
foreach ( var nonParagraphRunsParent in x.DescendantNodes().OfType<XElement>().Where( a => a.Parent != null && a.Name != null )
.Where( a => ( a.Name.LocalName == "r" ) ).Select( a => a.Parent ).Distinct().ToList() )
{
if ( lavaRegEx.IsMatch( nonParagraphRunsParent.Value ) )
{
var tempParent = XElement.Parse( new Paragraph().OuterXml );
tempParent.Add( nonParagraphRunsParent.Nodes() );
tempParent = MarkupSimplifier.MergeAdjacentSuperfluousRuns( tempParent );
nonParagraphRunsParent.ReplaceNodes( tempParent.Nodes() );
}
}
} );
XElement lastLavaNode = sourceTemplateDocX.DescendantNodes().OfType<XElement>().LastOrDefault( a => lavaRegEx.IsMatch( a.Value ) );
// ensure there is a { Next } indicator after the last lava node in the template
if (lastLavaNode != null)
{
var nextRecordMatch = nextRecordRegEx.Match( lastLavaNode.Value );
if ( nextRecordMatch == null || !nextRecordMatch.Success )
{
// if the last lava node doesn't have a { next }, append to the end
lastLavaNode.Value += " {% next %} ";
}
else
{
if ( !lastLavaNode.Value.EndsWith( nextRecordMatch.Value ) )
{
// if the last lava node does have a { next }, but there is stuff after it, add it (just in case)
lastLavaNode.Value += " {% next %} ";
}
}
}
bool? allSameParent = null;
using ( WordprocessingDocument outputDoc = WordprocessingDocument.Open( outputDocStream, true ) )
{
var xdoc = outputDoc.MainDocumentPart.GetXDocument();
var outputBodyNode = xdoc.DescendantNodes().OfType<XElement>().FirstOrDefault( a => a.Name.LocalName.Equals( "body" ) );
outputBodyNode.RemoveNodes();
int recordIndex = 0;
int? lastRecordIndex = null;
int recordCount = mergeObjectList.Count();
while ( recordIndex < recordCount )
{
if ( lastRecordIndex.HasValue && lastRecordIndex == recordIndex )
{
// something went wrong, so throw to avoid spinning infinitely
throw new Exception( "Unexpected unchanged recordIndex" );
}
lastRecordIndex = recordIndex;
using ( var tempMergeTemplateStream = new MemoryStream() )
{
sourceTemplateStream.Position = 0;
sourceTemplateStream.CopyTo( tempMergeTemplateStream );
//.........这里部分代码省略.........
示例12: DropNSFromDocument
void DropNSFromDocument (XDocument doc)
{
var attributes = doc.Descendants ().SelectMany (n => n.Attributes ());
var textNodes = doc.DescendantNodes().OfType<XText> ().ToArray();
DropNS (attributes, textNodes);
}
示例13: PrepareDocument
internal void PrepareDocument(XDocument document)
{
/* Remove all HTML comments (including conditional comments). */
document
.DescendantNodes()
.Where(node => node.NodeType == XmlNodeType.Comment
|| (node.NodeType == XmlNodeType.Element && "script" == GetElementName((XElement) node)))
.Remove();
/* In some cases a body element can't be found (if the HTML is totally hosed for example),
* so we create a new body element and append it to the document. */
XElement documentBody = GetOrCreateBody(document);
XElement rootElement = document.Root;
// TODO: handle HTML frames
var elementsToRemove = new List<XElement>();
/* Remove all noscript tags. */
elementsToRemove.Clear();
elementsToRemove.AddRange(rootElement.GetElementsByTagName("noscript"));
RemoveElements(elementsToRemove);
/* Remove all external stylesheets. */
elementsToRemove.Clear();
elementsToRemove.AddRange(
rootElement.GetElementsByTagName("link"));
RemoveElements(elementsToRemove);
/* Remove all style tags. */
elementsToRemove.Clear();
elementsToRemove.AddRange(rootElement.GetElementsByTagName("style"));
RemoveElements(elementsToRemove);
/* Remove all nav tags. */
elementsToRemove.Clear();
elementsToRemove.AddRange(rootElement.GetElementsByTagName("nav"));
RemoveElements(elementsToRemove);
/* Remove all anchors. */
elementsToRemove.Clear();
IEnumerable<XElement> anchorElements =
rootElement.GetElementsByTagName("a")
.Where(aElement => aElement.Attribute("name") != null && aElement.Attribute("href") == null);
elementsToRemove.AddRange(anchorElements);
RemoveElements(elementsToRemove);
/* Turn all double br's into p's and all font's into span's. */
// TODO: optimize?
/*不用做这个,最后 格式化的过程中会去掉多余的换行,同时会把所有的font等同普通文本
string bodyInnerHtml = documentBody.GetInnerHtml();
bodyInnerHtml = _ReplaceDoubleBrsRegex.Replace(bodyInnerHtml, "</p><p>");
bodyInnerHtml = _ReplaceFontsRegex.Replace(bodyInnerHtml, "<$1span>");
documentBody.SetInnerHtml(bodyInnerHtml);
* */
}
示例14: RemoveComments
//===========================================================================================
private void RemoveComments()
{
_Document = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory + @"\..\..\..\Xsd\MagickScript.xsd");
_Document.DescendantNodes().OfType<XComment>().Remove();
}
示例15: GetObjectFromXml
// __ Impl _______________________________________________________
private static ObjectData GetObjectFromXml(XDocument xmlDocument)
{
ObjectData currentObject = null;
FieldData currentField = null;
if (xmlDocument.DescendantNodes().Any())
{
currentObject = new ObjectData();
IEnumerable<XNode> nodes = xmlDocument.DescendantNodes();
foreach (dynamic node in nodes)
{
if (node is XElement)
{
string name = node.Name.LocalName;
var xnode = node as XElement;
switch (name)
{
case "object":
var nameElement =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "name");
if (nameElement != null)
currentObject.Name = nameElement.Value;
var settigsElement =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "settings");
if (settigsElement != null)
currentObject.IsSettingsInt = GetIntFromBoolString(settigsElement.Value);
currentObject.IsSingleInstInt =
GetIntFromBoolString(
xnode.Attributes()
.FirstOrDefault(a => a.Name.LocalName == "singleinstance")
.Value);
break;
case "description":
currentObject.Description = node.Value;
break;
case "field":
currentField = new FieldData();
currentField.Name =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "name").Value;
currentObject.FieldsIndexedByName.Add(currentField.Name, currentField);
if (IsClone(node))
{
currentField.CloneFrom(
currentObject.FieldsIndexedByName[
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "cloneof").Value]);
}
else
{
XAttribute typeElement =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "type");
if (typeElement != null)
{
string typeString = typeElement.Value;
currentField.TypeString = typeString;
currentField.Type = GetFieldTypeFromString(currentField.TypeString);
XAttribute elementsAttribute =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "elements");
if (elementsAttribute !=
null)
currentField.Elements = elementsAttribute.Value;
XAttribute unitsElement =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "units");
if (unitsElement != null)
currentField.Units = unitsElement.Value;
XAttribute elementNamesElement =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "elementnames");
if (
elementNamesElement !=
null)
currentField.ParseElementNamesFromAttribute(elementNamesElement.Value);
XAttribute optionsElement =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "options");
if (optionsElement !=
null)
currentField.ParseOptionsFromAttribute(optionsElement.Value);
XAttribute defaultValueElement =
xnode.Attributes().FirstOrDefault(a => a.Name.LocalName == "defaultvalue");
if (
defaultValueElement !=
null)
currentField.ParseDefaultValuesFromAttribute(defaultValueElement.Value);
}
}
currentObject.Fields.Add(currentField);
break;
case "option":
currentField.Options.Add(node.Value);
break;
case "elementname":
currentField.ElementNames.Add(node.Value);
break;
}
}
}
ExpandDefaultValues(currentObject);
SortFields(currentObject);
//.........这里部分代码省略.........