You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用C#的XDocument从XML文件读取属性值并赋值给变量?

How to Read XML Attribute Value into a Static C# String Using XDocument

Since you’ve already loaded your XML file into an XDocument instance with XDocument.Load(path), here’s a straightforward way to extract the myvalue from the name2 attribute and assign it to your static string variable:

Step-by-Step Implementation

First, declare your static variable (if you haven’t already), then retrieve the attribute value with proper null safety to avoid runtime errors:

// Your pre-loaded XDocument instance
XDocument xml_doc = XDocument.Load(path);

// Static string variable to store the XML attribute value
private static string new_my_var;

// Initialize the variable (place this in a static constructor or static method)
static YourClassName() // Replace "YourClassName" with your actual class name
{
    // Safely navigate through the XML structure to get the attribute
    XAttribute name2Attribute = xml_doc.Root?.Element("name")?.Attribute("name2");
    
    // Assign the value, defaulting to empty string if any part is missing
    new_my_var = name2Attribute?.Value ?? string.Empty;
}

Breakdown of the Code

  • xml_doc.Root: Directly accesses the root <root> element of your XML document (no need for Descendants("root") since XML only allows one root).
  • ?.Element("name"): Uses the null-conditional operator to safely get the child <name> element under the root—this prevents a NullReferenceException if the root is missing.
  • ?.Attribute("name2"): Safely retrieves the name2 attribute from the <name> element.
  • ?? string.Empty: Uses the null-coalescing operator to set new_my_var to an empty string if the attribute (or any parent element) doesn’t exist, avoiding a null value.

Simplified (Unsafe) One-Liner

If you’re 100% sure the XML structure will always match your expected format, you can use a shorter version (but this risks runtime errors if elements/attributes are missing):

private static string new_my_var = xml_doc.Root.Element("name").Attribute("name2").Value;

It’s always better to use the null-safe version to handle unexpected XML structure changes gracefully.


内容的提问来源于stack exchange,提问作者user11703431

火山引擎 最新活动