简体   繁体   中英

How to parse xml string element?

In C#, I have an xml string named inputXmlString like this:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:dd="clr-namespace:DiagramDesigner;assembly=GUI">
              <Setter.Value>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <LinearGradientBrush.GradientStops>
                    <GradientStop Color="#FFFAFBE9" Offset="0" />
                    <GradientStop Color="#FF00FFFF" Offset="1" />
                  </LinearGradientBrush.GradientStops>
                </LinearGradientBrush>
              </Setter.Value>
<TextBox Background="#00FFFFFF" Foreground="#FF000000" HorizontalAlignment="Center" VerticalAlignment="Center">Thread</TextBox>
</Grid>

Now I want to get the text of the TextBox element. For that I tried this method:

XElement inputElement = XElement.Parse(inputXmlString);
XElement textbox = inputElement.Element("TextBox");
string result = textbox.Value;

But the textbox element comes as null here. Any suggestion?

You have a namespace on your element, you need to specify it:

XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
XElement textbox = inputElement.Element(ns + "TextBox");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM