小编Mar*_*len的帖子

在XML文件中测试XPath的最佳方法是什么?

最近我一直在使用XPathDocument和XNavigator来解析给定XPath和属性的XML文件.当我事先知道XPath是什么时,它工作得非常好.

有时候,XPath将是几个可能的XPath值之一,我希望能够测试给定的XPath是否存在.

如果我的命名法错了,这就是我所谓的XPath - 给定这个XML blob:

<foo>
    <bar baz="This is the value of the attribute named baz">
</foo>
Run Code Online (Sandbox Code Playgroud)

我可能正在寻找我称之为"// foo/bar"的XPath,然后读取属性"baz"来获取值.

我用来执行此操作的代码示例:

XPathDocument document = new XPathDocument(filename);
XPathNavigator navigator = document.CreateNavigator();
XPathNavigator node = navigator.SelectSingleNode("//foo/bar");
if(node.HasAttributes)
{
    Console.WriteLine(node.GetAttribute("baz", string.Empty));
}
Run Code Online (Sandbox Code Playgroud)

现在,如果对navigator.SelectSingleNode的调用失败,它将返回NullReferenceException或XPathException.我可以捕获这两个并重构上面的测试,以查看给定的XPath是否返回异常,但我想知道是否有更好的方法?

我没有在Intellisense中看到任何明显的东西.XPathNavigator有.HasAttributes和.HasChildren但是没有一次遍历一个节点的路径,我没有看到任何更好的使用.

c# xml

6
推荐指数
1
解决办法
1万
查看次数

如何将图像添加到我的Run for RichTextBlock?

我写了一个小的WPF应用程序,我喜欢将文本添加到RichTextBox中,以便最新的东西在顶部.我写了这个,它有效:

    /// <summary>
    /// Prepends the text to the rich textbox
    /// </summary>
    /// <param name="textoutput">The text representing the character information.</param>
    private void PrependSimpleText(string textoutput)
    {
        Run run = new Run(textoutput);
        Paragraph paragraph = new Paragraph(run);

        if (this.RichTextBoxOutput.Document.Blocks.Count == 0)
        {
            this.RichTextBoxOutput.Document.Blocks.Add(paragraph);
        }
        else
        {
            this.RichTextBoxOutput.Document.Blocks.InsertBefore(this.RichTextBoxOutput.Document.Blocks.FirstBlock, paragraph);
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在我想制作一个新版本的功能,它也可以添加小图像.我虽然不知所措 - 是否可以添加图片?

c# wpf

1
推荐指数
1
解决办法
5406
查看次数

标签 统计

c# ×2

wpf ×1

xml ×1